在chrome扩展中分隔类

时间:2012-11-21 12:11:15

标签: google-chrome-extension

我正在编写我的第一个chrome扩展程序,我似乎无法找到以RequireJS类型方式提取功能的任何方法..

我只是希望能够在1个JS文件中编写一个类,并将其功能提取到我的background.js文件中并使用它,以保持整洁。

我google了,找不到任何东西!我错过了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

1

如果要将class.js功能提取到background.js中,只需将其附加到manifest.json中的脚本数组即可。

像这样,

{
  "name": "My extension",
  ...
  "background": {
    "scripts": ["class.js","background.js"]
  },
  ...
}

这意味着在加载class.js后将加载background.js。这样您就可以使用class.jsbackground.js的所有功能。


2

如果您想以require.js方式执行此操作,则应使用background.html而不是background.js

像这样,

的manifest.json

{
    "background": {
      "page": "background.html"
    },
    "description":  "Background example",
    "name":         "Background example",
    "version":      "0.0.1",
    "manifest_version": 2,
     "web_accessible_resources": [
       "scripts/require-jquery.js",
       "scripts/main.js"
    ],
}

如您所见,您必须添加将用于web_accesible_resource数组的脚本文件。

background.html

<!DOCTYPE html>
<html>
    <head>
        <title>jQuery+RequireJS Sample Page</title>
        <!-- This is a special version of jQuery with RequireJS built-in -->
        <script data-main="scripts/main" src="scripts/require-jquery.js"></script>
    </head>
    <body>
    </body>
</html>