I am building my first extension and have problems getting background page loaded scripts working in content scripts, which brings doubts to if any script loaded on the background page is really available to all content scripts.
I have two javascript files, functions.js and content.js, which both use jQuery. I load jQuery and the function script on the background page to decrease parsing with each site match. Once is enough as they are all functions.
manifest.json NON-WORKING
{
"name": "extension name",
"background_page": "background.html",
"content_scripts": [ {
"js": [ "js/functions.js", "js/content.js" ],
"matches": [ "http://*.mysite.com/*" ],
"exclude_globs": [ "*board*" ],
} ],
"version": "0.1"
}
Note: Using “include_globs” to load jQuery of a CDN doesnt work. Emulating @include is a failure, so I had to include jQuery with the extension.
manifest.json WORKING
{
"name": "extension name",
"background_page": "background.html",
"content_scripts": [ {
"js": [ "js/jquery-1.7.1.min.js", "js/functions.js", "js/content.js" ],
"matches": [ "http://*.mysite.com/*" ],
"exclude_globs": [ "*board*" ],
} ],
"version": "0.1"
}
Note: Here I removed loading jQuery on the background page.
background.html
<html>
<head>
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/functions.js"></script>
</head>
</html>
content.js
console.log('testing console'); // this works
alert('testing native JS'); // this works
$('<div id="myTestingDiv" />').prependTo('body'); // this fails
Background pages, pop-up pages and Content scripts all run in a different scope and document.
Any variables and script defined at the Background page are not directly accessible in Content scripts, and vice versa.
Injected Content scripts, on the other hand, can interact with each other.
You can get to the global (
window) objects using:windowof the Background page:chrome.extension.getBackgroundPage()windowobjects in the current extension:chrome.extension.getViews()