2016-10-12 68 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

相关问题