Chrome Extension: Make it run every page load

JavascriptGoogle ChromeGoogle Chrome-Extension

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

  }
})

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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!')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalbertoshView Question on Stackoverflow
Solution 1 - JavascriptfiatjafView Answer on Stackoverflow
Solution 2 - JavascriptMatchuView Answer on Stackoverflow
Solution 3 - JavascriptBohdanView Answer on Stackoverflow
Solution 4 - JavascriptVlad HilkoView Answer on Stackoverflow