【问题标题】:How to retrieve the element where a contextmenu has been executed如何检索已执行上下文菜单的元素
【发布时间】:2016-05-18 15:49:44
【问题描述】:

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

这是我的扩展的骨架:

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?

【问题讨论】:

  • 感谢您将此链接指向我,但我已经看到了这个问题。我已经尝试了注释 #7 中的解决方案,并且通过使用 document.activeElement 我检索了 HTMLBodyElement 而不是执行上下文菜单的输入文本元素。此外,评论 #14 提出的带有 jquery 的解决方案不起作用:我得到一个空值。
  • 您的内容脚本是否正在向后台脚本发送消息?是后台监听吗?

标签: javascript dom google-chrome-extension contextmenu


【解决方案1】:

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

manifest.json

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

内容脚本.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;
    });
}

【讨论】:

  • 非常感谢。解决方案是使用内容脚本来检索和更改当前选项卡中包含的字段的内容。确实,后台脚本是隔离的,无法访问当前网页的内容。然后,从内容脚本可以使用 document.activeElement
  • onRequest 和 sendRequest 现在已弃用。它应该是 onMessage 和 sendMessage。
  • 或者更好的是contextmenu event。在这种情况下,您不必检查event.button == 2
  • 如果只需要输入等可聚焦元素,可以改用document.activeElement
  • 我收到了Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
猜你喜欢
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多