注入Chrome扩展程序的内容脚本无法工作。

3

我已经对这个主题进行了大量研究,但仍有些不理解。我正在尝试制作一个简单的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
如果您的脚本没有被注入,您就不会得到控制台日志。因此,其他问题可能存在。 - Xan
1
此外,在这里根本不需要使用页面级注入。您只需将 script.js 代码放在 contentscript.js 中即可。页面级注入仅在需要绕过上下文隔离时才需要,而这在这里并不需要。 - Xan
1个回答

1

Here is an example:

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"
  ]
}

1
然而,我不希望用户必须点击扩展图标才能注入代码。我希望代码可以自动注入,因此当用户单击适当的超链接时,页面会被重定向到另一个URL。 - lizcoder
更新了我的回答。 - Alec von Barnekow
谢谢您的更新,但是这段代码对我来说不起作用...现在我甚至无法在控制台上打印任何内容。 - lizcoder
再次感谢——但是我仍然无法让它工作。 我甚至还没有看到测试消息记录到控制台中。 - lizcoder
inject.js文件是否已注入页面? - Alec von Barnekow
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接