为Chrome扩展程序注入内容脚本不起作用

时间:2016-10-12 21:44:23

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

我已经研究了很多这个话题,但是没有点击。我试图制作一个简单的Chrome扩展程序。细节并不重要,但基本上当用户点击某个网站上的某个按钮时,该页面会被重定向到不同的URL。我只是为了说明而放入虚拟URL。这是我的代码:

的manifest.json

{
    "manifest_version": 2,
    "name": "Blah",
    "version": "1.0",
    "description": "Blah blah",
    "icons": {  "16": "icon16.png",
            "48": "icon48.png",
            "128": "icon128.png" },
    "content_scripts": [
        {
        "matches": ["*://url1.com/*"],
        "js": ["contentscript.js"]
        }
    ],
    "web_accessible_resources": ["script.js"]
}

contentscript.js(在另一个Stack Overflow问题上发现这个问题,并不完全确定它是如何工作的)

var s = document.createElement("script");
s.src = chrome.extension.getURL("script.js");
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

的script.js

document.getElementById("id1").addEventListener("click", redirect);
function redirect() {
    console.log("Testing!");    // This works!
    window.location.replace("url2.org");
}

当我点击相应的按钮时,文本会记录到控制台,所以我知道我正在做正确的事情。但是,我猜测我实际上并没有将脚本注入页面,这就是为什么我的页面没有重定向的原因。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

以下是一个例子:

的script.js

// wait that page finished loading
window.addEventListener("load", function load(event){
// for the current tab, inject the "inject.js" file & execute it
    chrome.tabs.executeScript(tab.ib, {
        file: 'inject.js'
    });
},false);

inject.js

// this is the code which will be injected into a given page...

document.getElementById("id1").addEventListener("click", redirect);
function redirect() {
   console.log("Testing!");    // This works!
   window.location.replace("url2.org");
}

的manifest.json

{
  "name": "Inject",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "Injecting stuff",
  "content_scripts": [{
      "matches": ["http://example.com/*"],
       "js": ["script.js"]
  }],
  "permissions": [
    "http://example.com/*",
    "tabs"
  ]
}
相关问题