如何检测单击了超链接的右键单击上下文菜单中的哪个选项?

How to detect which option from hyperlink's right-clicked contextmenu was clicked?

假设我使用的是默认浏览器的上下文菜单。

已编辑:在关闭 link 的上下文菜单后立即替换剪贴板中的 link(即使用户选择了与 "Copy link location" 不同的选项)也是可以接受的解决方案。

不幸的是,出于安全原因,不可能检测在默认浏览器上下文菜单中选择的内容。

不可能 覆盖覆盖默认浏览器的默认功能/操作contextmenu 因为安全原因。

你能做什么:

  1. 使用浏览器扩展(最终用户应首先安装您的扩展),您可以将带有图标和功能的自定义选项添加到默认浏览器的上下文菜单中。

  2. 您可以覆盖鼠标右键单击时的默认行为。例如,右键单击后,您可以使用自己的功能显示自己的自定义上下文菜单。


编辑:我对 OP(原始海报)的第一条评论的回答:

右键单击和 oncotextmenu 事件后的 link 替换与您想在问题中实现的目标无关!我上面已经写过了

you can override default behaviour on mouse right click

这也意味着您可以在右键单击后替换 link,但在您的问题中,您希望在单击 特定菜单选项后替换 link 来自 默认 上下文菜单。出于安全原因,不可能

您必须阅读 oncontextmenu event:

The contextmenu event typically fires when the right mouse button is clicked on the window. Unless the default behavior is prevented, the browser context menu will activate.

Edited: replacing link in the clipboard RIGHT AFTER closing the link's contextmenu (even if user had chosen different option than "Copy link location") is also acceptable solution.

如果用户授予适当的permissions you can use contextmenu event, focusout attached to window within contextmenu event handler and Async Clipboard API

<body>
  <a id="a" href="#">click</a>
  <script>
    a.addEventListener('contextmenu', e => {
      console.log(e);
      window.addEventListener("focusout", e => {
        console.log(e);
        navigator.clipboard.writeText(a.href)
          .then(() => {
            console.log('Text copied to clipboard');
          })
          .catch(err => {
            // This can happen if the user denies clipboard permissions:
            console.error('Could not copy text: ', err);
          });
        navigator.clipboard.readText()
          .then(text => {
            console.log('Pasted content: ', text);
          })
          .catch(err => {
            console.error('Failed to read clipboard contents: ', err);
          });
      }, {
        once: true
      });
    });
  </script>
</body>

plnkr

contextmenu用于标识right click 例如:

$('{IdOrClass}').on('click contextmenu', "a", function(event) {
   alert("Right clicked"); // do whatever you want on right click
});