r3x*_*r3x 2 javascript google-chrome contextmenu google-chrome-extension
有没有办法显示上下文菜单操作,只有当用户右键单击以"story"开头的类时.
例如:如果用户右键单击类"story ...."页面中的对象,则应显示上下文菜单按钮,否则不会发生任何事情.
这是我的代码(尽管它不起作用):
var divs = document.querySelectorAll("[class^=story]"); //get all classes that start with "Story"
window.oncontextmenu = function() {
for(var i=0; i < divs.length; i++)
{
divs[i].onclick = function() {
chrome.contextMenus.create
(
{"id": "butto1", "title": "1", "contexts":["all"], "onclick": genericOnClick}
);
chrome.contextMenus.create
(
{"id": "button2", "title": "2", "contexts":["all"], "onclick": genericOnClick}
);
chrome.contextMenus.create
(
{"id": "button3", "title": "3", "contexts":["all"], "onclick": genericOnClick}
);
};
}
return true;
};
function genericOnClick(info, tab) {
//do some crap here
chrome.contextMenus.removeAll();
}
Run Code Online (Sandbox Code Playgroud)
在这个相关的答案中,我解释了无法动态创建上下文菜单项,因为contextmenu事件和上下文菜单项的外观之间的时间不足以chrome.contextMenus.create在两者之间进行调用.
另一个答案解释了如何确保上下文菜单条目显示所选文本.这是通过听取selectionchange事件来完成的.为了您的目的,我们希望使用具有所需时间的事件.
我将使用mouseover和mouseout事件.通过依赖鼠标事件,当您使用键盘时,上下文菜单将不起作用,例如,通过使用JavaScript或Tab键聚焦元素,然后按上下文菜单键.我没有在下面的解决方案中实现它.
该演示包含三个文件(以及一个用于测试它的HTML页面).我将所有文件放在一个zip文件中,可在https://robwu.nl/contextmenu-dom.zip获得.
manifest.json每个Chrome扩展程序都需要此文件才能运行.对于此应用程序,使用后台页面和内容脚本.此外,contextMenus还需要许可.
{
"name": "Contextmenu based on activated element",
"description": "Demo for https://stackoverflow.com/q/14829677",
"version": "1",
"manifest_version": 2,
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"run_at": "document_idle",
"js": ["contentscript.js"],
"matches": ["<all_urls>"]
}],
"permissions": [
"contextMenus"
]
}
Run Code Online (Sandbox Code Playgroud)
background.js后台页面将代表内容脚本创建上下文菜单.这是通过绑定事件监听器来实现的chrome.runtime.onConnect,它提供了一个简单的接口来替换上下文菜单条目.
chrome.contextMenus.create只要通过此端口(从内容脚本)收到消息,就会调用此方法.除了onclickJSON可序列化之外的所有属性,因此只有"onclick"处理程序需要特殊处理.我用字符串来识别字典中的预定义函数(var clickHandlers).
var lastTabId;
// Remove context menus for a given tab, if needed
function removeContextMenus(tabId) {
if (lastTabId === tabId) chrome.contextMenus.removeAll();
}
// chrome.contextMenus onclick handlers:
var clickHandlers = {
'example': function(info, tab) {
// This event handler receives two arguments, as defined at
// https://developer.chrome.com/extensions/contextMenus#property-onClicked-callback
// Example: Notify the tab's content script of something
// chrome.tabs.sendMessage(tab.id, ...some JSON-serializable data... );
// Example: Remove contextmenus for context
removeContextMenus(tab.id);
}
};
chrome.runtime.onConnect.addListener(function(port) {
if (!port.sender.tab || port.name != 'contextMenus') {
// Unexpected / unknown port, do not interfere with it
return;
}
var tabId = port.sender.tab.id;
port.onDisconnect.addListener(function() {
removeContextMenus(tabId);
});
// Whenever a message is posted, expect that it's identical to type
// createProperties of chrome.contextMenus.create, except for onclick.
// "onclick" should be a string which maps to a predefined function
port.onMessage.addListener(function(newEntries) {
chrome.contextMenus.removeAll(function() {
for (var i=0; i<newEntries.length; i++) {
var createProperties = newEntries[i];
createProperties.onclick = clickHandlers[createProperties.onclick];
chrome.contextMenus.create(createProperties);
}
});
});
});
// When a tab is removed, check if it added any context menu entries. If so, remove it
chrome.tabs.onRemoved.addListener(removeContextMenus);
Run Code Online (Sandbox Code Playgroud)
contentscript.js该脚本的第一部分创建了用于创建上下文菜单的简单方法.
在最后5行中,定义上下文菜单条目并将其绑定到与给定选择器匹配的所有当前和未来元素.就像我在上一节中所说的那样,参数类型与"onclick" 的createProperties参数chrome.contextMenus.create相同,"onclick"是一个映射到后台页面中的函数的字符串.
// Port management
var _port;
var getPort = function() {
if (_port) return _port;
_port = chrome.runtime.connect({name: 'contextMenus'});
_port.onDisconnect.addListener(function() {
_port = null;
});
return _port;
}
// listOfCreateProperties is an array of createProperties, which is defined at
// https://developer.chrome.com/extensions/contextMenus#method-create
// with a single exception: "onclick" is a string which corresponds to a function
// at the background page. (Functions are not JSON-serializable, hence this approach)
function addContextMenuTo(selector, listOfCreateProperties) {
// Selector used to match an element. Match if an element, or its child is hovered
selector = selector + ', ' + selector + ' *';
var matches;
['matches', 'webkitMatchesSelector', 'webkitMatches', 'matchesSelector'].some(function(m) {
if (m in document.documentElement) {
matches = m;
return true;
}
});
// Bind a single mouseover+mouseout event to catch hovers over all current and future elements.
var isHovering = false;
document.addEventListener('mouseover', function(event) {
if (event.target && event.target[matches](selector)) {
getPort().postMessage(listOfCreateProperties);
isHovering = true;
} else if(isHovering) {
getPort().postMessage([]);
isHovering = false;
}
});
document.addEventListener('mouseout', function(event) {
if (isHovering && (!event.target || !event.target[matches](selector))) {
getPort().postMessage([]);
isHovering = false;
}
});
}
// Example: Bind the context menus to the elements which contain a class attribute starts with "story"
addContextMenuTo('[class^=story]', [
{"id": "butto1", "title": "1", "contexts":["all"], "onclick": 'example'},
{"id": "button2", "title": "2", "contexts":["all"], "onclick": 'example'},
{"id": "button3", "title": "3", "contexts":["all"], "onclick": 'example'}
]);
Run Code Online (Sandbox Code Playgroud)
前面的代码假定所有上下文菜单点击都由后台页面处理.如果要改为处理内容脚本中的逻辑,则需要在内容脚本中绑定消息事件.我展示的(评论)实例chrome.tabs.sendMessage中的background.js例子,显示此事件应该被触发.
如果您需要识别触发事件的元素,请不要使用我的示例中所示的预定义函数(在字典中),而是使用内联函数或工厂函数.要识别元素,需要将消息与唯一标识符配对.我将把这个实现的任务留给读者(这并不困难).
| 归档时间: |
|
| 查看次数: |
2251 次 |
| 最近记录: |