[英]How to get a reference for TITLE, in chrome.contextMenus.create onClick function?
[英]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(鼠标右键)时将消息发送到Background 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引起关注
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.