本文介绍了chrome 扩展上下文菜单,如何仅在没有选择时显示菜单项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是:

如果用户没有选择任何东西,则显示菜单项A;

if the user does not select anything, display menu item A;

如果用户选择了某些内容,则显示菜单项 B.

if the user selects something, display menu item B.

目前我能得到的是:

如果用户没有选择任何东西,则显示菜单项A;

if the user does not select anything, display menu item A;

如果用户选择了某些内容,则同时显示 A 和 B.

if the user selects something, display both A and B.

我想知道:

有选择时如何让A项消失?

how to make item A disappear when there is selection?

非常感谢!

下面是我的代码:

var all = chrome.contextMenus.create
({
    "title": "A",
    "contexts":["page"],
    "onclick": doA
});

var selection = chrome.contextMenus.create
({
    "title": "B",
    "contexts":["selection"],
    "onclick": doB
});

推荐答案

您需要向每个页面注入一个内容脚本来检查 mousedown 事件(在菜单显示之前)是否页面上有一个选择,然后会向后台页面发送命令以创建相应的菜单项.

You would need to inject a content script to every page which would check on mousedown event (before menu is displayed) whether or not there is a selection on the page, and then would send a command to a background page to create according menu items.

content_script.js:

document.addEventListener("mousedown", function(event){
    //right click
    if(event.button == 2) {
        if(window.getSelection().toString()) {
            chrome.extension.sendRequest({cmd: "createSelectionMenu"});
        } else {
            chrome.extension.sendRequest({cmd: "createRegularMenu"});
        }
    }
}, true);

background.html

chrome.extension.onRequest.addListener(function(request) {
    if(request.cmd == "createSelectionMenu") {
        chrome.contextMenus.removeAll(function() {
            chrome.contextMenus.create({
                "title": "B",
                "contexts":["selection"],
                "onclick": doB
            });
        });
    } else if(request.cmd == "createRegularMenu") {
        chrome.contextMenus.removeAll(function() {
            chrome.contextMenus.create({
                "title": "A",
                "contexts":["page"],
                "onclick": doA
            });
        });
    }
});

这篇关于chrome 扩展上下文菜单,如何仅在没有选择时显示菜单项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:35