由于 Chrome 不允许您使用上下文菜单与您单击的元素进行交互,因此您必须创建一个 content script 来存储最后一个被右键单击的元素在页面上,因此当用户右键单击任何元素时,您将能够使用它。
首先您必须创建一个save_last_element.js 内容脚本,如下所示:
var LAST_SELECTION,
LAST_ELEMENT;
document.body.addEventListener('contextmenu', function(e) {
LAST_SELECTION = window.getSelection();
LAST_ELEMENT = e.target;
// this will update your last element every time you right click on some element in the page
}, false);
然后你将它添加到你的manifest.json:
"permissions": ["*://*/*"],
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["/path/to/save_last_element.js"],
"run_at": "document_idle",
"all_frames": true
}
]
现在,当在页面中注入脚本时,您将能够使用 LAST_SELECTION 和 LAST_ELEMENT 变量来引用最后一次右键单击的元素并编辑其 CSS 或任何您想要的内容。
在您的background.js 中,您应该这样做:
function handler(info, tab) {
// here you can inject a script inside the page to do what you want
chrome.tabs.executeScript(tab.id, {file: '/path/to/script.js', allFrames: true});
}
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
"title": "Some title",
"contexts": ["all"],
"documentUrlPatterns": ["*://*/*"],
"onclick": handler
});
});
请注意,上下文菜单是在 chrome.runtime.onInstalled 监听器中注册的,因为上下文菜单注册是持久的,只需要在安装扩展程序时完成。
最后,在您的 script.js 文件中:
if (LAST_SELECTION) {
// do whatever you want with the information contained in the selection object
}
if (LAST_ELEMENT) {
// do whatever you want with the element that has been right-clicked
}