如何在 contextMenus onclick 事件处理程序中获取 iframeId?

How to get iframeId in a contextMenus onclick event handler?

我正在开发 Mozilla WebExtension。我只想将 JavaScript 文件注入到我单击了使用 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 先生找到了解决这种情况的方法,

首先,我在 manifest.json 文件的所有帧中注入了 "messageListener.js" 文件作为

"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" 是我要发送消息的 web 扩展的 id。

然后,在我的后台 js 文件中,我声明了名为 "clickedFrameID" 的全局变量,并在同一文件中添加了 onMessage Listener,如下所示

browser.runtime.onMessage.addListener(
    function(msg, sender, callback) {
         if(msg.type === 'onContextMenuClicked')
            {
               if(sender.hasOwnProperty("frameId")){
                   clickedFrameID=sender.frameId;
               }else{
                   clickedFrameID="";
               }
            }
}); 

现在我已经将 "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" 将被注入到我右击的特定帧中。

感谢@wOxxOm、@MohammedAshrafali、@Makyen 的关注