Chrome扩展程序中的Require.JS:未定义define

Vov*_*cev 9 javascript scope google-chrome google-chrome-extension requirejs

我正在尝试在我的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"
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

hd_init.js

console.log("hello, i'm init");

require.config({
    baseUrl: chrome.extension.getURL("js")
});

require( [ "js/test"], function ( ) {
    console.log("done loading");
});
Run Code Online (Sandbox Code Playgroud)

JS/test.js

console.log("hello, i'm test");
define({"test_val":"test"});
Run Code Online (Sandbox Code Playgroud)

这是我在控制台中得到的:

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 
Run Code Online (Sandbox Code Playgroud)

所以它加载文件,但看不到"定义"功能.这看起来像某种范围错误.如果我在本地服务器上运行,它可以正常工作.

有任何想法吗?

non*_*arn 7

内容脚本中有两种上下文.一个用于浏览器,另一个用于扩展.

您将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);
};
Run Code Online (Sandbox Code Playgroud)