gpt4 book ai didi

javascript - Chrome 扩展中的 Require.JS : define is not defined

转载 作者:数据小太阳 更新时间:2023-10-29 03:53:10 26 4
gpt4 key购买 nike

我正在尝试在我的 chrome 扩展程序中使用 Requre.js。

这是我的 list :

{
"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);
};

关于javascript - Chrome 扩展中的 Require.JS : define is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10759130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com