我希望我的插件可以处理任何页面的加载并更改其中的一些内容,因为我已经编写了内容脚本,并在外部js文件中添加了外部js文件,我无法访问chrome.tab。我做错了吗?
------内容脚本----
debugger;
var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
(document.head||document.documentElement).appendChild(s);
s.parentNode.removeChild(s);
/*chrome.runtime.sendMessage('3645374', 'any message',[] , function(){ alert('---...---'); } ) ;
chrome.tabs.executeScript(null, {file: "doWhatYouWant();"});
document.addEventListener('DOMContentLoaded', function() {
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
(document.head||document.documentElement).appendChild(s);
s.parentNode.removeChild(s);
chrome.tabs.executeScript(null, {code:"doWhatYouWant();"});
}
});
});*/
-------------------- script.js --------------
function doWhatYouWant(){
alert('inside .... doWhatYouWant');
document.getElementById('zx12').value = "CHANGED !";
}
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
debugger;
alert('I am here too ');
// Execute some script when the page is fully (DOM) ready
chrome.tabs.executeScript(null, {code:"doWhatYouWant();"});
}
});
/*chrome.extensions.onRequest.addLiestener( function(p1,p2,p3){
alert('done');
document.getElementById('zx12').value = "CHANGED !";
});
chrome.runtime.onMessage.addListener(function (){
alert('doWhatYouWant called');
});
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('zx12').value = "CHANGED !";
});
*/
----------------------- manifest.json ---------------
{
"name": "My Chrome Extension",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [{
"matches": ["http://*/*","https://*/*"],
"js": ["jquery.js","contentscript.js"]
}],
"web_accessible_resources" : ["script.js"],
"permissions": [
"activeTab"
]
}
答案 0 :(得分:2)
内容脚本无法使用大多数Chrome扩展程序API。 (您正在进行的chrome.extension.getURL
调用是一种罕见的例外。)您可能需要在扩展的后台页面中实现chrome.tabs
事件侦听器,并将消息传递给内容脚本。
请阅读the Google Chrome documentation on content scripts,特别是有关限制的介绍部分和有关执行环境的部分。