简体   繁体   English

为Chrome扩展程序注入内容脚本无效

[英]Injecting content script for Chrome extension isn't working

I've researched this topic a ton but something isn't clicking. 我已经研究了这个话题,但有些事情并没有点击。 I'm trying to make a simple Chrome extension. 我正在尝试制作一个简单的Chrome扩展程序。 The details aren't important, but basically when the user clicks on a certain button on a certain website, the page is redirected to a different URL. 细节并不重要,但基本上当用户点击某个网站上的某个按钮时,该页面会被重定向到不同的URL。 I've put in dummy URLs just for illustration. 我只是为了说明而放入虚拟URL。 Here is my code: 这是我的代码:

manifest.json 的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 (found this on another Stack Overflow question, not totally sure how it works) 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 的script.js

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

The text is logged to the console when I click the appropriate button, so I know I'm doing something right. 当我单击相应的按钮时,文本会记录到控制台,所以我知道我正在做正确的事情。 However, I'm guessing I'm not actually injecting the script into the page, and that's why my page isn't redirecting. 但是,我猜我实际上并没有将脚本注入页面,这就是我的页面没有重定向的原因。 Any help would be appreciated! 任何帮助,将不胜感激!

Here is an example: 这是一个例子:

script.js 的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 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 的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"
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM