【问题标题】:Chrome extension is not runing auto. Content scripts not executingChrome 扩展程序未自动运行。内容脚本未执行
【发布时间】:2017-08-20 01:53:55
【问题描述】:

我正在尝试使用 Google Chrome 扩展程序,我遇到的第一个问题是我想在页面加载时自动更改正文背景颜色(不点击扩展程序图标),但我的内容脚本没有启动:

ma​​nifest.json:

{
  "name": "Test Extension",
  "description": "Testing",
  "version": "1.0",
  "permissions": [
    "tabs", "webNavigation"
  ],
  "browser_action": {
      "default_title": "Set this page's color.",
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  },
  "content_scripts": [
  {
  "matches": ["http://*/*", "https://*/*"],
  "js": ["core.js"]
  }
  ],  
  "background": {
    "scripts": ["background.js"]
  },

  "manifest_version": 2
}

core.js:

chrome.tabs.executeScript(null,{code:'document.body.style.backgroundColor = "green";'});

不工作的解决方案background.js:

chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
    chrome.tabs.executeScript(null,{file:"core.js"});
});

问题出在哪里?请寻求帮助。

【问题讨论】:

  • 查看有关如何编写内容脚本的文档。 core.js 是代码所在,而不是执行脚本。
  • 只写:window.onload=function(){ document.body.style.backgroundColor = "green";而是在你的 core.js 文件中执行脚本
  • 我已经完成了,似乎 core.js 没有运行...
  • @Edenwave 为什么不呢?你在哪里尝试什么?我试试这个,它对我有用
  • 我将 core.js 的代码更改为您在上一个答案中输入的代码。核心没有执行,我不知道为什么。

标签: javascript google-chrome plugins google-chrome-extension manifest


【解决方案1】:

为您提供更好的解决方案,它只是使用内容脚本并等到加载而不执行脚本:

manifest.json

 {
  "name": "Test Extension",
  "description": "Testing",
   "version": "1.0",
   "permissions": [
     "tabs", "webNavigation"
   ],
   "browser_action": {
   "default_title": "Set this page's color.",
   "default_icon": "icon.png",
   "default_popup": "popup.html"
    },
   "content_scripts": [
   {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["core.js"],
      "run_at": "document_end"
   }
 ],  
 "manifest_version": 2
}

core.js

  window.onload=function(){ 
   console.log("test!!");
   document.body.style.backgroundColor = "green"; }

popup.html 不管在这里。 我只是尝试一下,它可以在任何站点(您可以在 stackoverflow 上尝试)和控制台中将背景颜色更改为绿色。

【讨论】:

  • 我真的不知道为什么,但现在它正在工作......谢谢 OriEng。
猜你喜欢
  • 1970-01-01
  • 2015-12-24
  • 2016-09-09
  • 2013-03-09
  • 2019-11-05
  • 2012-05-09
  • 2023-03-19
  • 1970-01-01
  • 2016-01-02
相关资源
最近更新 更多