38

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

JustMe
  • 6,065
  • 3
  • 19
  • 17

1 Answers1

81

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
}
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Thanks Rob W, but I have a lot of code after the check statements, I can't write it after "code:'" can I call a function? – JustMe Mar 25 '12 at 17:17
  • 8
    @user1291538 You can put it in a separate file within the extension, and use `file: 'nameoffile.js'` instead of `'code': '...'` - See also the [linked documentation](http://code.google.com/chrome/extensions/tabs.html#method-executeScript). – Rob W Mar 25 '12 at 17:19
  • 1
    Is there a way to check for onCompleted event for only a particular TAB ID. I need this because I don't want to injectScript on multiple tabs loading as the code needs to only be run one tab at a time and not on multiple tabs of a website. I want to have it such that I can inject the script to the tab im working with based on the tab Id. – John Yepthomi Jul 18 '21 at 18:34