由于 Chrome 不允许您使用上下文菜单与您单击的元素进行交互,因此您必须创建一个内容脚本它存储页面上右键单击的最后一个元素,因此当用户右键单击任何元素时,您将能够使用它。
首先你必须创建一个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
and LAST_ELEMENT
变量来引用最后一个右键单击的元素并编辑其 CSS 或任何您想要的内容。
In your 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
file:
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
}