我正在尝试基于所选内容创建Chrome上下文菜单条目。
我在Stackoverflow上找到了几个与此有关的问题,在所有这些问题中,答案都是:使用带有“mousedown”侦听器的内容脚本来查看当前选择并创建上下文菜单。
我已经实现了这一点,但它并不总是有效。有时所有日志消息都显示上下文菜单已按照我的要求修改,但出现的上下文菜单没有更新。
基于此,我怀疑这是一种竞争条件:有时Chrome在代码完全运行之前开始渲染上下文菜单。
我尝试添加“contextmenu”和“mouseup”的eventListener。后者会在用户用鼠标选择文本时触发,因此会在上下文菜单出现之前(甚至几秒钟之前)更改上下文菜单。即使使用这种技术,我仍然看到发生相同错误的情况!
这在Chrome 22.0.1229.94(Mac)中经常发生,在Chromium 20.0.1132.47(Linux)中偶尔发生,并且在Windows上尝试了2分钟(Chrome 22.0.1229.94)没有发生。
到底发生了什么?我该如何解决?还有其他的解决办法吗?
这是我代码的简化版本(不太简单,因为我保留了日志消息):
manifest.json:
{
"name": "Test",
"version": "0.1",
"permissions": ["contextMenus"],
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["content_script.js"]
}],
"background": {
"scripts": ["background.js"]
},
"manifest_version": 2
}
内容脚本.js
function loadContextMenu() {
var selection = window.getSelection().toString().trim();
chrome.extension.sendMessage({request: 'loadContextMenu', selection: selection}, function (response) {
console.log('sendMessage callback');
});
}
document.addEventListener('mousedown', function(event){
if (event.button == 2) {
loadContextMenu();
}
}, true);
background.js
function SelectionType(str) {
if (str.match("^[0-9]+$"))
return "number";
else if (str.match("^[a-z]+$"))
return "lowercase string";
else
return "other";
}
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
console.log("msg.request = " + msg.request);
if (msg.request == "loadContextMenu") {
var type = SelectionType(msg.selection);
console.log("selection = " + msg.selection + ", type = " + type);
if (type == "number" || type == "lowercase string") {
console.log("Creating context menu with title = " + type);
chrome.contextMenus.removeAll(function() {
console.log("contextMenus.removeAll callback");
chrome.contextMenus.create(
{"title": type,
"contexts": ["selection"],
"onclick": function(info, tab) {alert(1);}},
function() {
console.log("ContextMenu.create callback! Error? " + chrome.extension.lastError);});
});
} else {
console.log("Removing context menu")
chrome.contextMenus.removeAll(function() {
console.log("contextMenus.removeAll callback");
});
}
console.log("handling message 'loadContextMenu' done.");
}
sendResponse({});
});