当从我的后台脚本中单击上下文菜单时,我试图将活动的 dom 元素传递给通过 chrome.tabs.executeScript 调用的脚本。我可以很好地传递布尔值和字符串,但是当我传递 dom 元素时总是会出错。我开始认为这是不可能的。
//doScripts function called from browser action
chrome.browserAction.onClicked.addListener(function(tab) {
doScripts(true, null);
});
//doScripts function called from context menu click
function getClickHandler(info, tab) {
var currTarg = document.activeElement;
console.log("currTarg = " + currTarg);
doScripts(false, currTarg);
}
//i reference doingBrowserAction and contextTarg in myscript.js
function doScripts(context, targ){
chrome.tabs.executeScript(null, {code: "var doingBrowserAction = "+context+"; var contextTarg = "+targ+";"}, function(){
chrome.tabs.executeScript(null, {file: "js/myscript.js"}, function(){
//all injected
});
});
}
//setup context menu
chrome.contextMenus.create({
"title" : "DESTROY!",
"type" : "normal",
"contexts" : ["page","selection","link","editable","image","video","audio"],
"onclick" : getClickHandler
});
我在 myscript.js 中引用了doingBrowserAction 和 contextTarg。我知道我正在尝试做的事情是可能的,因为 adblock 扩展可以做到这一点,但很难弄清楚如何做。提前致谢。