RequireJS in a Chrome extension

Here is how you can do it in the background page.

In manifest.json:

"background": {
    "scripts": [ "scripts/require.js","scripts/main.js"]
}, 

In main.js:

require.config({
    baseUrl: "scripts"
});

require( [ /*...*/ ], function(  /*...*/ ) {
    /*...*/
});

Instead of this:

<script data-main="scripts/bla" src="scripts/require.js></script>

You should use this:

<script src="scripts/require-jquery.js"></script>
<script src="scripts/main.js"></script>

See this question - Using Require.js without data-main

You can also do the same thing in the content page using this principle.

Nice Question by the way. I liked Adam Ayres's answers.


You do have access to the DOM of the page from the Chrome Extension via a content script, however the content script will only have access to the JavaScript objects created by the content script itself.

There are many ways to include scripts from a Chrome extension, how you include it will be based on what you plan to do with it.

If you want it in the popup page of a browser or page action you can either include it from the manifest as a content script or reference it using a script tag in the popup.html from a relative resource in your plugin.

From manifest:

{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "css": ["mystyles.css"],
      "js": ["jquery.js", "myscript.js"]
    }
  ],
  ...
}

From popup.html:

<script data-main="scripts/bla" src="scripts/require-jquery.js>

If you want it in the background page you can reference it from the background page using a script tag from a relative resource in your plugin.

From background.html

<script data-main="scripts/bla" src="scripts/require-jquery.js>

If you want it to be included in the browser page itself then you need to use dynamic script injection on the page's DOM. You have access to the page's DOM from a content script. Please note that if you load the JavaScript using this technique you plugin JavaScript (from a background page, content script or popup script) will not have access to it.

You can either load the requirejs from your extension using the chrome.extension.getURL method or from the a hosted location on the internet.

var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.setAttribute("async", true);
script.setAttribute("src", chrome.extension.getURL("require-jquery.js"));  
//Assuming your host supports both http and https
var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
head.insertBefore(script, head.firstChild)