Chrome 扩展程序中的页面加载事件 [英] On page load event in Chrome extensions
问题描述
我想在 chrome 浏览器页面完全加载时检查内容中的一些值就这样
I want to check some values in the content of chrome browser page when it completely loaded like that
if(document.body.innerText.indexOf("Cat") !=-1)
我可以在何时何地进行支票?请给我一个明确的例子我读了一些关于Background.html"和内容脚本"的东西,但我做不到
Where and when can I make my check? please give me an clear example I read some thing about "Background.html" and "Content script" but I can't do
推荐答案
在manifest 文件位于 "run_at": "document_idle"
(这是默认设置)并将您的代码放入内容脚本文件中.然后脚本将在页面准备好时运行.
Register a content script in the manifest file at "run_at": "document_idle"
(which is the default) and put your code in the content script file. Then the script will be run when the page is ready.
如果要从后台页面检测页面是否完全加载,请使用 chrome.webNavigation.onCompleted
事件并做任何你想做的事情,比如调用 chrome.tabs.executeScript
执行内容脚本.如果 URL 列表是动态的,或者无法使用 匹配模式语法.
If you want to detect from the background page whether a page is completely loaded, use the chrome.webNavigation.onCompleted
event and do whatever you want, such as calling chrome.tabs.executeScript
to execute a content script. This method could be useful over the previous method if the list of URLs is dynamic or if the URL patterns cannot be described using the match pattern syntax.
chrome.webNavigation.onCompleted.addListener(function(details) {
chrome.tabs.executeScript(details.tabId, {
code: ' if (document.body.innerText.indexOf("Cat") !=-1) {' +
' alert("Cat not found!");' +
' }'
});
}, {
url: [{
// Runs on example.com, example.net, but also example.foo.com
hostContains: '.example.'
}],
});
webNavigation
和主机权限必须在 manifest 中设置.json
,例如:
The webNavigation
and host permissions have to be set in manifest.json
, e.g.:
{
"name": "Test",
"version": "1.0",
"background": { "scripts": ["background.js"] },
"permissions": [ "webNavigation", "*://*/*" ],
"manifest_version": 2
}
这篇关于Chrome 扩展程序中的页面加载事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!