Javascript Chrome 扩展:让它在每个页面加载时运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6497548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Chrome Extension: Make it run every page load
提问by albertosh
I want to make a chrome extension that executes some scripts after one page is loaded, I am not sure whether I have to implement this logic on the background page or it can be anywhere else, any help here will be greatly appreciated.
我想制作一个在页面加载后执行一些脚本的 chrome 扩展,我不确定我是否必须在后台页面上实现这个逻辑,或者它可以在其他任何地方,这里的任何帮助将不胜感激。
回答by fiatjaf
From a background scriptyou can listen to the chrome.tabs.onUpdated
event and check the property changeInfo.status
on the callback. It can be loadingor complete. If it is complete, do the action.
从后台脚本中,您可以侦听chrome.tabs.onUpdated
事件并检查changeInfo.status
回调的属性。它可以是正在加载或已完成。如果已完成,请执行操作。
Example:
例子:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
// do your things
}
})
Because this will probably trigger on every tab completion, you can also check if the tab is active
on its homonymous attribute, like this:
因为这可能会在每个选项卡完成时触发,您还可以检查选项卡是否active
在其同名属性上,如下所示:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
// do your things
}
})
回答by Matchu
If it needs to run on the onload
event of the page, meaning that the document and all its assets have loaded, this needs to be in a content scriptembedded in each page for which you wish to track onload
.
如果它需要onload
在页面事件上运行,这意味着文档及其所有资产都已加载,则这需要嵌入在您希望跟踪的每个页面中的内容脚本中onload
。
回答by Bohdan
回答by Evan Ross
This code should do it:
这段代码应该这样做:
manifest.json
清单文件
{
"name": "Alert 'hello world!' on page opening",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
]
}
content.js
内容.js
alert('Hello world!')