116

I want to make a chrome extension that executes some scripts after one page is loaded, I am not sure whether I have to implement this logic on the background page or it can be anywhere else, any help here will be greatly appreciated.

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
albertosh
  • 2,416
  • 7
  • 25
  • 32
  • just in case, it should run the script after any page is loaded in the browser. – albertosh Jun 27 '11 at 18:57
  • @ZloySmiertniy yes, just look for content scripts, also make sure that in the run_at option you put document_end and also in matches: you need to specify in which url's your scripts will be injected. – albertosh May 25 '17 at 19:52
  • 1
    If you just want to run a script on a page for yourself, you could also do that with [Tampermonkey](https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en) – Benedikt Köppel Feb 02 '22 at 09:18

4 Answers4

125

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

  }
})
Mike Frysinger
  • 2,827
  • 1
  • 21
  • 26
fiatjaf
  • 11,479
  • 5
  • 56
  • 72
47

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.

Omer M.
  • 630
  • 7
  • 17
Matchu
  • 83,922
  • 18
  • 153
  • 160
  • 16
    It would be better to let the content script be injected at "document_end" see "run_at" within the content_script manifest: `run_at: "document_end"` – Mohamed Mansour Jun 27 '11 at 23:12
  • 1
    @MohamedMansour well, it depends… since content scripts are limited to examining the DOM, its co-habitating webpage may have gotten busy earlier, and thus may have permanently mutated or deleted nodes already by that time, which you didn’t get to see and now will never know about.. – Glenn Slayden Dec 16 '22 at 10:22
41

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

Omer M.
  • 630
  • 7
  • 17
Bohdan
  • 1,987
  • 16
  • 23
39

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!')
Vlad Hilko
  • 1,104
  • 12
  • 17