Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

On page load event in Chrome extensions

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)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.'
    }],
});

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...