[英]Require.JS in a Chrome extension: define is not defined
我正在嘗試在我的chrome擴展中使用Requre.js。
這是我的清單:
{
"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"});
這是我在控制台中得到的:
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
所以它加載文件,但看不到“定義”功能。 這看起來像某種范圍錯誤。 如果我在本地服務器上運行,它可以正常工作。
有任何想法嗎?
內容腳本中有兩種上下文。 一個用於瀏覽器,另一個用於擴展。
您將require.js加載到擴展上下文中。 但require.js將依賴項加載到瀏覽器上下文中。 define
未在瀏覽器中定義。
我寫了一個關於這個問題的(未經測試的)補丁。 要使用它,請在require.js之后將其加載到擴展上下文中。 您的模塊將加載到擴展上下文中。 希望這可以幫助。
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);
};
現在推薦的方法是使用cajon( https://github.com/requirejs/cajon/ )。 請參閱https://groups.google.com/d/msg/requirejs/elU_NYjunRw/3NT9NIFL2GUJ 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.