页面加载完成后,这根本不会触发。基本上,当我单击浏览器操作按钮时,它将触发它,并且在页面加载时,它将运行脚本。在我的background.js中
var toggle = false; chrome.browserAction.onClicked.addListener(function(tab) { toggle = !toggle; if(toggle){ chrome.browserAction.setIcon({path: "icons/logo.png", tabId:tab.id}); // chrome.tabs.executeScript(tab.id, {file:"SCRIPT.user.js"}); chrome.tabs.executeScript(tab.id, {code:"alert('aaxxxbbaa')"}); } else{ chrome.browserAction.setIcon({path: "icons/icon48.png", tabId:tab.id}); chrome.tabs.executeScript(tab.id, {code:"alert('bbdxdb')"}); } }); var filter = {'url': [ {hostSuffix: '*', pathPrefix: ''}, {hostSuffix: '*', pathPrefix: ''} ]}; chrome.webNavigation.onDOMContentLoaded.addListener(function(tab){ if (toggle) chrome.tabs.executeScript(tab.id,{code:"alert('loaded')"}); },filter);
我也尝试将其设置在清单中
{ "name": "Tool", "version": "0.0.1", "manifest_version": 2, "description": "Te", "homepage_url": "", "icons": { "16": "icons/logo.png", "48": "icons/logo.png", "128": "icons/logo.png" }, "default_locale": "en", "background": { "page": "src/bg/background.html", "persistent": true }, "browser_action": { "default_icon": "icons/logo.png", "default_title": "browser action demo" }, "permissions": [ "" ], "content_scripts": [ { "run_at": "document_end", "matches": [ "https://www.google.ca/*" ], "css": [ "src/inject/inject.css" ] }, { "run_at": "document_end", "matches": [ "https://www.google.ca/*" ], "js": [ "src/inject/inject.js" ] } ] }
在我的inject.js中
chrome.extension.sendMessage({}, function(response) { var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); // ---------------------------------------------------------- // This part of the script triggers when page is done loading console.log("Hello. This message was sent from scripts/inject.js"); // ---------------------------------------------------------- } }, 10); }); window.addEventListener ("load", myMain, false); function myMain (evt) { console.log('aaann'); var jsInitChecktimer = setInterval (checkForJS_Finish, 111); function checkForJS_Finish () { if ( typeof SOME_GLOBAL_VAR != "undefined" || document.querySelector ("SOME_INDICATOR_NODE_css_SELECTOR") ) { clearInterval (jsInitChecktimer); // DO YOUR STUFF HERE. console.log('hi'); } } }
kylehuff.. 5
在清单文件中,您有重复的内容脚本,一个包含CSS,一个包含JS。它看起来应该像这样:
"content_scripts": [ { "run_at": "document_end", "matches": [ "https://www.google.ca/*" ], "js": [ "src/inject/inject.js" ], "css": [ "src/inject/inject.css" ] } ]
另外,如果您希望它与其他网址匹配,则需要专门添加它们,或使用
"matches": [""]
至于您建议的背景脚本,这实际上是在重新发明内容脚本的概念,并且可能不符合您的最大利益。我建议坚持使用内容脚本路由。