Chrome扩展上下文菜单,如何仅在没有选择时显示菜单项? [英] chrome extension context menus, how to display a menu item only when there is no selection?
问题描述
我想要做的是:
如果用户不选择任何内容,则显示菜单项A;
如果用户选择了某项内容,则显示菜单项B。
到目前为止我可以得到的是:
同时显示A和B.
我想知道:
如何使物品A在选择时消失
非常感谢!
下面是我的代码:
var all = chrome.contextMenus.create
({
title: A,
contexts:[page],
onclick:doA
});
var selection = chrome.contextMenus.create
({
title:B,
contexts:[selection],
onclick:doB
});
您需要为每个页面它会检查 mousedown
事件(显示菜单之前)是否在页面上有选择,然后将命令发送到后台页面以根据菜单创建
content_script.js:
document.addEventListener(mousedown,function(event){
//右击
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
}) ;
});
}
});
What I want to do is:
if the user does not select anything, display menu item A;
if the user selects something, display menu item B.
So far what I can get is:
if the user does not select anything, display menu item A;
if the user selects something, display both A and B.
I want to know:
how to make item A disappear when there is selection?
Many thanks!
Below is my code:
var all = chrome.contextMenus.create
({
"title": "A",
"contexts":["page"],
"onclick": doA
});
var selection = chrome.contextMenus.create
({
"title": "B",
"contexts":["selection"],
"onclick": doB
});
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扩展上下文菜单,如何仅在没有选择时显示菜单项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!