← 中文资源

简体中文版本

auxclick 承接 click 不管的中键与右键

click 只响应主键;中键(button 1)与未被右键菜单消费的次键走 auxclick——自定义中键行为、记录未消费右键都在这里接,不影响链接默认的后台开新标签。

阅读英文原文

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 跑完文件,输出里会留下标记——unclaimed secondary click, detail:。

常见问题

「auxclick 承接 click 不管的中键与右键」能在裸 Node.js 里跑吗?

不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

核心语句

const anchor = event.target.closest('a[href]');

代码示例

// click fires only for the primary button; auxclick covers auxiliary
// buttons: middle (button 1) and secondary (button 2) presses that the
// context menu did not claim.
document.addEventListener('auxclick', (event) => {
  if (event.button === 1) {
    const anchor = event.target.closest('a[href]');
    console.log(anchor ? `middle click on ${anchor.getAttribute('href')}` : 'middle click outside a link');
    return;
  }
  if (event.button === 2) {
    console.log('unclaimed secondary click, detail:', event.detail);
  }
});

// Middle-click already opens a background tab on links; auxclick is the
// hook for extra behavior — logging, analytics opt-outs, custom routing.