2016-10-12 67 views
3

我已經研究過這個話題,但沒有點擊。我正在嘗試製作一個簡單的Chrome擴展程序。細節並不重要,但基本上當用戶點擊某個網站上的某個按鈕時,頁面會重定向到不同的URL。我已經輸入了虛擬URL,僅用於說明。這裏是我的代碼:爲Chrome擴展插入內容腳本不起作用

的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(找到另一個堆棧溢出問題,它不能完全確定是如何工作的)

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"); 
} 

當我點擊相應的按鈕時,文本被記錄到控制檯,所以我知道我在做som正確。不過,我猜測我並沒有將腳本實際注入頁面,這就是爲什麼我的頁面沒有重定向。任何幫助,將不勝感激!

+1

如果你的腳本沒有注入,你不會得到控制檯日誌。所以別的是一個問題。 – Xan

+1

此外,根本不需要使用頁面級注入。你可以簡單地把你的'script.js'代碼放在你的'contentscript.js'中。頁面級注入僅用於繞過[上下文隔離](https://developer.chrome.com/extensions/content_scripts#execution-environment),這裏不需要。 – Xan

回答

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

但是,我不希望用戶必須單擊要注入的代碼的擴展名圖標。我想讓代碼自動注入,所以當用戶點擊適當的超鏈接時,頁面被重定向到另一個URL。 – lizcoder

+0

已更新我的回答 – Fralec

+0

感謝您的更新,但代碼不適合我...現在甚至無法將任何內容打印到控制檯。 – lizcoder

相關問題