我对这个主题进行了大量研究,但有些东西没有点击。我正在尝试制作一个简单的 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/