将代码移动到单独的函数

时间:2017-04-08 21:59:10

标签: javascript google-chrome google-chrome-extension contextmenu

我正在开发Google Chrome扩展程序。

我遇到同样的问题:Right click menu disappears after restarting the browser

解决方案是使用:

chrome.runtime.onInstalled .addListener(function(){ chrome.runtime.onStartup .addListener(function(){

我已经对它进行了测试,但它确实有效,但现在我有了重复的代码:

//context menu
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
    title: '1',
    id: 'a',
    contexts: ['all'],
});
});
chrome.runtime.onStartup.addListener(function() {
chrome.contextMenus.create({
    title: '1',
    id: 'a',
    contexts: ['all'],
});
});

如何缩短代码?我是JavaScript的新手,非常感谢!

1 个答案:

答案 0 :(得分:1)

您可以单独定义创建上下文菜单的函数,然后将该函数作为参数传递给addListener

function createContextMenu() {
  chrome.contextMenus.create({
    title: '1',
    id: 'a',
    contexts: ['all']
  });
}

chrome.runtime.onInstalled.addListener(createContextMenu);
chrome.runtime.onStartup.addListener(createContextMenu);
相关问题