簡體   English   中英

為Chrome擴展程序注入內容腳本無效

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

我已經研究了這個話題,但有些事情並沒有點擊。 我正在嘗試制作一個簡單的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");
}

當我單擊相應的按鈕時,文本會記錄到控制台,所以我知道我正在做正確的事情。 但是,我猜我實際上並沒有將腳本注入頁面,這就是我的頁面沒有重定向的原因。 任何幫助,將不勝感激!

這是一個例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM