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

标签 javascript google-chrome google-chrome-extension scope requirejs

我正在尝试在我的 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/

相关文章:

javascript - 禁用仅在生产环境 sails js 中运行的 Grunt 任务?

android - Android 设备上的 Ionic 2 中未显示 Typescript sourcemaps

html - 使 "special"在 Chrome 中移动的 Div 宽度

javascript - 不安全的 CSP 值 "' unsafe-eval '"in directive ' script-src'

asynchronous - 如何从异步函数设置全局变量

javascript - 捕获特定字符之前的单词

javascript - 如何使用 CSS 和 HTML 创建水平 TreeView ?

css - Chrome 扩展 - iFrame 自动高度

javascript - `await` 命令导致变量失去作用域

linux - Chrome Kiosk 模式会忽略缩放设置