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?
To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.
This usually happens because your JavaScript environment doesn't understand how to handle the call to require() function you defined in your code. Here are some known causes for this error: Using require() in a browser without RequireJS. Using require() in Node.
To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With