如何检索已执行上下文菜单的元素 [英] How to retrieve the element where a contextmenu has been executed

查看:22
本文介绍了如何检索已执行上下文菜单的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个使用上下文菜单的 google chrome 扩展程序.此上下文菜单仅可用于可编辑元素(例如输入文本).单击并执行上下文菜单时,我想在回调函数中检索已执行上下文菜单的元素(输入文本),以便更新与此输入文本关联的值.

I am trying to write a google chrome extension where I use a contextmenu. This contextmenu is available on editable elements only (input texts for example). When the contextmenu is clicked and executed I would like to retrieve in the callback function the element (the input text) on which the contextmenu has been executed in order to update the value associated to this input text.

这是我的扩展的骨架:

function mycallback(info, tab) {
  // missing part that refers to the question:
  // how to retrieve elt which is assumed to be 
  // the element on which the contextMenu has been executed ?
  elt.value = "my new value"
}

var id = chrome.contextMenus.create({
        "title": "Click me",
        "contexts": ["editable"],
        "onclick": mycallback
    });

与 mycallback 函数关联的参数不包含检索右键单击元素的有用信息.这似乎是一个已知问题(http://code.google.com/p/chromium/issues/detail?id=39507) 但几个月以来没有任何进展.有人知道解决方法:不使用 jquery 和/或使用 jquery?

The parameters associated to the mycallback function contain no useful information to retrieve the right clicked element. It seems this is a known issue (http://code.google.com/p/chromium/issues/detail?id=39507) but there is no progress since several months. Does someone knows a workaround: without jquery and/or with jquery?

推荐答案

您可以使用 contextmenu 事件监听器和存储被点击的元素来注入内容脚本:

You can inject content script with contextmenu event listener and store element that was clicked:

manifest.json

"content_scripts": [{
  "matches": ["<all_urls>"],
  "js": ["content.js"],
  "all_frames": true,
  "match_about_blank": true
}]

content script.js

//content script
var clickedEl = null;

document.addEventListener("contextmenu", function(event){
    clickedEl = event.target;
}, true);

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if(request == "getClickedEl") {
        sendResponse({value: clickedEl.value});
    }
});


background.js

//background
function mycallback(info, tab) {
    chrome.tabs.sendMessage(tab.id, "getClickedEl", {frameId: info.frameId}, data => {
        elt.value = data.value;
    });
}

这篇关于如何检索已执行上下文菜单的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆