Chrome extension code vs Content scripts vs Injected scripts
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 viachrome.extension.getBackgroundPage()
, such as the browser pop-ups.Content scripts (via the manifest file or
chrome.tabs.executeScript
) - Partial access to some of thechrome
APIs, full access to the page's DOM (not to any of thewindow
objects, including frames).
Content scripts run in a scope between the extension and the page. The globalwindow
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();"});
}
});