我在安装扩展程序时无法执行一些安装代码。我正在使用Chrome开发者页面建议的chrome.runtime.onInstall,但未启动。似乎该问题与Require.JS的使用有关。这是我的代码:
requirejs.config({...});// i'll not reproduce the whole config here for brevity
// Define the Global Object that will hold the extension functionality
var EXT = EXT || {};
// Start the main app logic.
requirejs(['chrome.storage', 'chrome.settings', 'chrome.tabs'],
function (chromeStorage, chromeSettings, chromeTabs) {
'use strict';
var getLocalRepos;
/**
* Executes the callback with an array of repositories as the parameter.
* @param {function} callback
*/
getLocalRepos = function (callback) {
'use strict';
chromeStorage.get('localRepos', callback);
};
// Take care of the extension lifecycle.
chrome.runtime.onInstalled.addListener(function (details) {
"use strict";
// Create dummy data to populate the local storage for testing purposes.
var dummyData = [
{
name: 'repo1',
description: 'description1',
username: 'reydel',
age: 'theAge'
},
{
name: 'repo2',
description: 'description2',
username: 'reydel',
age: 'theAge'
}
];
switch (details.reason) {
case 'install':
chromeStorage.set({ localRepos: dummyData }, function () {
// Do nothing
});
break;
}
});
// Bind all functions to an object in the Global Space to make them accessible from the outside scripts
// referencing the BackgroundPage object
window.EXT.getLocalRepos = getLocalRepos;
});
我已经在控制台中的侦听器的回调中使用了代码,并且可以正常工作,只是事件没有被触发。
关于如何解决这个问题的任何想法?有人做过吗?
chrome.runtime.onInstalled
加载代码后直接触发该事件。异步添加事件侦听器时,则在onInstalled
添加事件侦听器时已经调度了该事件。
要解决此问题,您必须使应用程序的初始化同步。不幸的是,require.js被设计为异步脚本加载器。修改该库以使其同步是可能的,但是浪费了精力却没有任何好处。
要在Chrome扩展程序中使用需求样式模块(AMD),我强烈建议您使用一个将脚本(例如r.js或grunt-contrib-requirejs)和almond.js组合为脚本加载器的中间构建步骤。与require.js相反,almond.js确实支持同步加载。
这是一个配置示例,可用于构建一个名为all.js
almond.js(作为脚本加载器)并mymain.js
用作入口点(主脚本)的文件:
({
name: 'mymain',
out: 'all.js',
include: [
'almond'
],
skipModuleInsertion: true,
wrap: {
start: '(function(){',
// true = load synchronously. This is a feature of almond.js
end: 'require(["mymain"], null, null, true);})();'
}
})
为了避免命名空间污染,我将代码包装在立即调用的函数表达式中。如果您希望模块在全局名称空间中可用(例如,用于调试),只需删除(function(){
和即可})();
。
有关这些配置选项(以及更多)的文档,请参见https://github.com/jrburke/r.js/blob/master/build/example.build.js。
要尝试前面的示例:
r.js
:npm install -g requirejs
myfancyname.build.js
mymain.js
:define(function() { ... });
。r.js -o myfancyname.build.js
all.js
可以加载一个名为的文件,例如,通过"background": { "scripts": ["all.js"] }
在Chrome扩展程序的清单文件中使用。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句