Chrome 扩展: 让它运行每个页面加载

我想做一个铬扩展,执行一些脚本后,一个页面加载,我不知道是否我必须实现这个逻辑在后台页面或它可以在其他任何地方,任何帮助在这里将非常感谢。

148811 次浏览

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 script embedded in each page for which you wish to track onload.

You can put your script into a content-script, see

From a background script you can listen to the chrome.tabs.onUpdated event and check the property changeInfo.status on the callback. It can be loading or complete. If it is complete, do the action.

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:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {


// do your things


}
})

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

alert('Hello world!')