javascript - 在非持久性后台脚本上添加上下文菜单项?

标签 javascript google-chrome google-chrome-extension

我正在使用以下方法从非持久性后台脚本添加上下文菜单项:

chrome.contextMenus.create({
  title: 'Get Code',
  id: 'myUniqueIdForThisExtension123',
  contexts: ['all'],
  onclick: onClickHandler
});

function onClickHandler() {}

documentation简单地说:

The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension.

所以我添加了一个唯一的ID,但我仍然不能让它工作。上下文菜单中没有插入任何新内容。

最佳答案

你是说你有一个非持久性背景页面,所以你应该有一个看起来像这样的 manifest.json 文件:

{
    "manifest_version": 2,

    "name": "My extension",
    "description": "My description",
    "version": "1",
    
    "permissions": ["contextMenus"],
    "background": {
        "persistent": false,
        "scripts": [
            "/background.js"
        ] 
    }
}

现在,由于您有一个非持久性后台页面,因此当您需要使用上下文菜单时,您必须使用正确的监听器来“唤醒它”。

引自official documentation (注意:此链接指向 2014 年文档的存档副本并且已过时):

Best practices when using event pages:

[...]

  1. If you're using the context menus API, pass a string id parameter to contextMenus.create, and use the contextMenus.onClicked callback instead of an onclick parameter to contextMenus.create.

所以,很简单,您的错误是在 background.js 中使用 onclick 参数而不是 contextMenus.onClicked.addListener() 方法>.

解决方案

我已经说过你应该使用onClicked事件,但我想补充一点,引用x a's answer :

You should register a context menu via contextMenus.create in the event handler of runtime.onInstalled, as these context menu registrations persist anyway.

很简单,一旦创建了上下文菜单,它就会保留在您的扩展中,最好只定义一次:当您的扩展被安装(或更新)时,并在每次加载后台页面时添加监听器.

chrome.runtime.onInstalled.addListener(function() {
    chrome.contextMenus.create({
        title: 'My menu',
        id: 'menu1', // you'll use this in the handler function to identify this context menu item
        contexts: ['all'],
    });
});

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    if (info.menuItemId === "menu1") { // here's where you'll need the ID
        // do something
    }
});

这就是您在事件页面中创建上下文菜单所需要的,如 documentation page 中所示 chrome.contextMenus API。

关于javascript - 在非持久性后台脚本上添加上下文菜单项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26245888/

相关文章:

javascript - Express 4使用multer作为中间件出现错误

javascript - 将 PHP 数组发送到回显字符串中调用的 JS 函数

jquery - 使用 jQuery 选项卡的谷歌浏览器 "An invalid form control is not focusable"

javascript - Chrome 扩展 js : Sharing functions between background. js 和 popup.js

javascript - MarkLogic - Node.js 客户端 API - QueryBuilder - 需要数据页和查询的完整计数

javascript - 如何防止点击 "Select all"复选框影响表头和列排序

asp.net-mvc - MVC HTTPS localhost Chrome 连接不安全 NET::ERR_CERT_COMMON_NAME_INVALID

javascript - 选择开始忽略 Chrome 中文本区域中的新行/换行符

Javascript:这个条件有什么问题?

css - 如何使用内容脚本将 <style> 注入(inject)带有 Chrome 扩展的页面的头部