Require.JS in a Chrome extension: define is not defined

google-chrome, google-chrome-extension, javascript, requirejs, scope

Solution

There are two contexts in content scripts. One is for browser, another is for extension.

You load require.js into the extension context. But require.js loads dependencies into the browser context. `define` is not defined in the browser.

I wrote a (untested) patch about this problem. To use this, load this into extension context after require.js. Your modules will be loaded into extension context. Hope this helps.

require.attach = function (url, context, moduleName, onScriptLoad, type, fetchOnlyFunction) {
  var xhr;
  onScriptLoad = onScriptLoad || function () {
    context.completeLoad(moduleName);
  };
  xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.onreadystatechange = function (e) {
    if (xhr.readyState === 4 && xhr.status === 200) {
      eval(xhr.responseText);
      onScriptLoad();
    }
  };
  xhr.send(null);
};

Problem

I'm trying to use Requre.js in my chrome extension. Here is my manifest: ``` { "name":"my extension", "version":"1.0", "manifest_version":2, "permissions": ["http://localhost/*"], "web_accessible_resources": [ "js/test.js" ], "content_scripts":[ { "matches":["http://localhost/*"], "js":[ "js/require.js", "js/hd_init.js" ] } ] } ``` hd_init.js ``` console.log("hello, i'm init"); require.config({ baseUrl: chrome.extension.getURL("js") }); require( [ "js/test"], function ( ) { console.log("done loading"); }); ``` js/test.js ``` console.log("hello, i'm test"); define({"test_val":"test"}); ``` This is what I get in console: ``` hello, i'm init chrome-extension://bacjipelllbpjnplcihblbcbbeahedpo/js/hd_init.js:8 hello, i'm test test.js:8 **Uncaught ReferenceError: define is not defined test.js:2** done loading ``` So it loads the file, but can't see "define" function. This looks like some kind of a scope error. If I run in on local server, it works as it should. Any ideas?

Original source