0

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
Kim
  • 2,747
  • 7
  • 41
  • 50

1 Answers1

3

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:

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • +1. In particular, see the [discussion of isolated worlds](http://code.google.com/chrome/extensions/content_scripts.html#execution-environment) in the ContentScripts documentation for details about how exactly this works. – Mike West Mar 06 '12 at 16:11
  • For executing code within the scope of a web page, see [this answer](http://stackoverflow.com/a/8994454/938089?how-to-disable-facebook-hotkeys-with-chrome-extension). For a demo on adding a method to support `chrome.*` methods in the injected code, see the bottom green block at [**this diff**](http://userscripts.org/scripts/diff/112070/440352). – Rob W Mar 06 '12 at 16:23