How to get iframeId in eventMenus onclick event handler?

I am developing WebExtension for Mozilla. I want to add a JavaScript file only to the frame into which I clicked the context menu select button created using contextMenus.create() .

I use:

 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"); }); } 

How to get clickedFrameID ?

+5
source share
1 answer

After being tested so much (by Chandrakant Thakkar) and my team leader Mr. Nitin Makwan got a solution for this situation,

First I entered the messageListener.js file into all frames from the manifest.json file as

 "content_scripts": [ { "matches": ["https://*/*","http://*/*"], "css":["jquery-ui.css"], "js": [ "jquery.js", "jquery-ui.js", "content_scripts/msg_listener.js" ], "all_frames":true } 

Then, in the messageListener.js file, a "contextMenu" listener is created and the message is sent to the js background file when the context menu is pressed (right-click) a

 document.addEventListener("contextmenu", handleContextMenu, false); function handleContextMenu(event){ browser.runtime.sendMessage(" abc@gmail.com ",{type: "onContextMenuClicked", sender:event }); } 

here, " abc@gmail.com " is the identifier of my web extension where I want to send the message.

Then, in my background, a js file that I declared in a global variable named "clickedFrameID", and in the same file I added onMessage Listener, as shown below

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

Now I have entered fileName.js in a specific frame as below

  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"); }); } 

Now "fileName.js" will be entered in a specific frame since I right-clicked.

Thanks @wOxxOm, @MohammedAshrafali, @Makyen to interest

+3
source

Source: https://habr.com/ru/post/1270564/


All Articles