我正在开发 Mozilla WebExtension。我只想将 JavaScript 文件注入(inject)到我单击使用 contextMenus.create()
创建的上下文菜单选项的框架中。
我正在使用:
browser.contextMenus.create({
"title": "Records",
"contexts": ["all","link"],
"id" : "M1",
"onclick": onClickContextMenu,
}, function() { });
function onClickContextMenu(info, tab){
var clickedFrameID=""; //How do I get the actual frameId where click occurred?
browser.tabs.executeScript(tab.id,{
file: "fileName.js",
allFrames: false,
frameId: clickedFrameID
}, function() {
console.log("Script injected");
});
}
如何获取clickedFrameID
?
最佳答案
经过多次测试,我(Chandrakant Thakkar)和我的团队领导 Nitin Makwana 先生找到了针对这种情况的解决方案,
首先,我将“messageListener.js”文件从manifest.json 文件中注入(inject)到所有框架中
"content_scripts": [
{
"matches": ["https://*/*","http://*/*"],
"css":["jquery-ui.css"],
"js": [
"jquery.js",
"jquery-ui.js",
"content_scripts/msg_listener.js"
],
"all_frames":true
}
然后在“messageListener.js”文件中创建“contextMenu”监听器,并在单击 contextMenu(鼠标右键单击)时将消息发送到后台 js 文件 作为
document.addEventListener("contextmenu", handleContextMenu, false);
function handleContextMenu(event){
browser.runtime.sendMessage("abc@gmail.com",{type:
"onContextMenuClicked", sender:event });
}
此处,“abc@gmail.com”是我要向其发送消息的网络扩展的 ID。
然后,在我的后台 js 文件中,我声明了名为“clickedFrameID”的全局变量,并在同一文件中添加了 onMessage 监听器,如下所示
browser.runtime.onMessage.addListener(
function(msg, sender, callback) {
if(msg.type === 'onContextMenuClicked')
{
if(sender.hasOwnProperty("frameId")){
clickedFrameID=sender.frameId;
}else{
clickedFrameID="";
}
}
});
现在我已在特定框架中注入(inject)“fileName.js”文件,如下所示
var clickedFrameID=""; //This is a Global Variable
browser.contextMenus.create({
"title": "Records",
"contexts": ["all","link"],
"id" : "M1",
"onclick": onClickContextMenu,
}, function() { });
function onClickContextMenu(info, tab){
var options={};
if(clickedFrameID !="" && clickedFrameID!=null &&
clickedFrameID!=undefined )
{
options={
file: "fileName.js",
allFrames: false,
frameId: clickedFrameID
};
}
browser.tabs.executeScript(tab.id,options, function() {
console.log("Script injected");
});
}
现在“fileName.js”将被注入(inject)到我右键单击的特定框架中。
感谢@wOxxOm、@MohammedAshrafali、@Makyen 的关注
关于javascript - 如何在 contextMenus onclick 事件处理程序中获取 iframeId?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45500135/