Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 341
JustMe Avatar asked Mar 25 '12 17:03

JustMe


1 Answers

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
}
like image 137
Rob W Avatar answered Oct 20 '22 07:10

Rob W