I am trying to get my Chrome Extension to run the function init()
whenever a new page is loaded, but I am having trouble trying to understand how to do this. From what I understand, I need to do the following in background.html:
chrome.tabs.onUpdated.addListener()
to check when the page is
changedchrome.tabs.executeScript
to run a script.This is the code I have:
//background.html
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
chrome.tabs.executeScript(null, {code:"init();"});
});
//script.js
function init() {
alert("It works!");
}
I am also wondering if the init() function will have access to my other functions located in other JS files?
JavaScript code in Chrome extensions can be divided in the following groups:
Extension code - Full access to all permitted chrome.*
APIs.
This includes the background page, and all pages which have direct access to it via chrome.extension.getBackgroundPage()
, such as the browser pop-ups.
Content scripts (via the manifest file or chrome.tabs.executeScript
) - Partial access to some of the chrome
APIs, full access to the page's DOM (not to any of the window
objects, including frames).
Content scripts run in a scope between the extension and the page. The global window
object of a Content script is distinct from the page/extension's global namespace.
Injected scripts (via this method in a Content script) - Full access to all properties in the page. No access to any of the chrome.*
APIs.
Injected scripts behave as if they were included by the page itself, and are not connected to the extension in any way. See this post to learn more information on the various injection methods.
To send a message from the injected script to the content script, events have to be used. See this answer for an example. Note: Message transported within an extension from one context to another are automatically (JSON)-serialised and parsed.
In your case, the code in the background page (chrome.tabs.onUpdated
) is likely called before the content script script.js
is evaluated. So, you'll get a ReferenceError
, because init
is not .
Also, when you use chrome.tabs.onUpdated
, make sure that you test whether the page is fully loaded, because the event fires twice: Before load, and on finish:
//background.html
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
// Execute some script when the page is fully (DOM) ready
chrome.tabs.executeScript(null, {code:"init();"});
}
});