将代码移至单独的函数

Moving code to a separate function

我正在开发 Google Chrome 扩展。

我也有这样的问题:Right click menu disappears after restarting the browser

解决方案是使用:

chrome.runtime.onInstalled.addListener(函数() { chrome.runtime.onStartup.addListener(函数() {

我已经测试过了,它可以工作,但现在我有重复的代码:

//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 的新手,非常感谢!

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

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

chrome.runtime.onInstalled.addListener(createContextMenu);
chrome.runtime.onStartup.addListener(createContextMenu);