Chrome 扩展上下文菜单在更新后不工作

Chrome Extension Context Menu not working after update

我有一个扩展程序,我最近推送了一个具有更新权限的更新。一些用户正在升级并报告更新后该应用程序无法运行,为了使其再次运行,他们必须完全卸载该应用程序并重新安装,一切正常。

有没有人遇到过类似的问题?对我来说,在测试所有正确更新的内容时,并不是每个人都有这个问题,但它正在成为一个问题。

需要注意的一点 - 弹出选项卡确实有效,只是上下文菜单有问题。

编辑 - 我无法复制并且除了从用户那里获取报告之外没有明确的方法来测试它。在部署另一个更新后,我确实注意到报告有所下降,我调整了权限的顺序......我完全看不出这有什么关系,但我正在寻找关于为什么会发生这种情况以及是否存在的任何澄清可以做些什么来避免将来发生这种情况。

您正在为 chrome.runtime.onInstalled event. This is the documented and recommended way to create context menu items, but it is not always triggered due to bugs in Chrome (crbug.com/388231, crbug.com/389631, crbug.com/264963).

在侦听器中创建上下文菜单项

我猜在你的情况下,权限更新导致扩展被禁用,然后 chrome.runtime.onInstalled 在重新启用它后不再被触发,因为 crbug.com/388231.

此错误的解决方法是使用较短的计时器并尝试更新本应创建的上下文菜单项。如果未触发 onInstalled 事件,则不会创建上下文菜单并且尝试更新它会失败。然后可以使用此条件来确保正确创建上下文菜单。

var SOME_CONTEXTMENU_ID = "GifMeContextMenu";

function onInstalled() {
    // ... do your thing, e.g. creating a context menu item:
    chrome.contextMenus.create({
        "title": "GifMe",
        "contexts": ["image"],
        "id": SOME_CONTEXTMENU_ID
    });
}

// Should be triggered whenever the extension or browser is
// reloaded, installed or updated.
chrome.runtime.onInstalled.addListener(onInstalled);

setTimeout(function() {
    // This .update() call does not change the context menu if it exists,
    // but sets chrome.runtime.lastError if the menu does not exist.
    chrome.contextMenus.update(SOME_CONTEXTMENU_ID, {}, function() {
        if (chrome.runtime.lastError) {
            // Assume that crbug.com/388231 occured, manually call the
            // onInstalled handler.
            onInstalled();
        }
    });
}, 222); // <-- Some short timeout.