0

我正在尝试为 Firefox 和 Chrome 编写跨浏览器扩展。Firefox 使用 commonJS 规范,而 Chrome 只是将所有内容都集中到全局命名空间中,就像网页一样。

为了能够编写可重用的代码,我正在尝试使用 requireJS 在 Chrome 扩展中加载代码,这样我就可以编写 commonJS 模块并让它们在两种环境中工作。

当我需要有条件地需要模块时,我遇到了问题。例如,Firefox 提供对simple-storage您应该用来访问本地存储的模块的访问。在 chrome 中,我需要使用他们提供的 localStorage API。所以,我一直在尝试这样做:

// storage.js
define(function(require, exports, module){
  var store;      

  try {
    // This module will only be available in the FF extension.
    store = require('simple-storage').storage
  } catch(error) {
    // If it's not available, we must be in Chrome and we
    // should use the localStorage object.
    store = localStorage
  }

  // Use the store object down here.
});

但是,这似乎不起作用。当我尝试加载 Chrome 扩展程序时,出现以下错误:

铬错误

有没有更好的方法来要求具有后备功能的模块?

4

1 回答 1

0

这里有两个警告:

1)检测chrome是否正在运行

// detects webKit (chrome, safari, etc..)
var isChrome = 'webKitTransform' in document.documentElement.style

2) Requirejs 会解析define()函数并搜索require('module')调用。为了防止 chrome 上的错误,您以某种方式编写了requirerequirejs解析函数体时它不会将调用识别为模块依赖项的方式:

if (isChrome)
   // use localStorage
else {
   // set the module name in a var does the trick,
   // so requirejs will not try to load this module on chrome.
   var ffStorageModule = 'simple-storage';
   return require(ffStorageModule);
}
于 2012-08-24T15:38:55.483 回答