使用要点
- 用到了
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.