javascript - 为 Chrome 扩展程序注入(inject)内容脚本不起作用

标签 javascript google-chrome google-chrome-extension

我对这个主题进行了大量研究,但有些东西没有点击。我正在尝试制作一个简单的 Chrome 扩展。细节并不重要,但基本上当用户单击某个网站上的某个按钮时,页面会重定向到不同的 URL。我输入了虚拟 URL 只是为了说明。这是我的代码:

list .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);

脚本.js

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

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

最佳答案

这是一个例子:

脚本.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"
  ]
}

关于javascript - 为 Chrome 扩展程序注入(inject)内容脚本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40008879/

相关文章:

javascript - react 保存使用重新渲染组件选择文本的可能性

javascript - 如何让我的脚本从 30 个随机 div 中生成 12 个 - Jquery

jquery - 使用 jquery 数据查看器扩展 google chrome 元素检查器

javascript - 谷歌浏览器。从命令行启动离线模式

javascript - Auth.currentSession 表示没有当前用户

Javascript:删除span标签中最后出现的逗号

html - 如何在 Chrome 中查看 mime 类型?它在 "document"选项卡下显示 "Network"

google-chrome-extension - 如何构建像 Google Hangouts 这样的 chrome 扩展程序

javascript - 阻塞 chrome.webRequest.onBeforeSendHeaders 监听器中的异步操作

javascript - 如何获取 Google Plus 通知数量?