本文介绍了确保内容脚本可以看到 `click` 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Chrome 编写一个扩展程序,用于监听和捕获用户的点击事件.这是我捕获事件的方式

I'm writing an extension for Chrome that listen and capture the click events made by the user.This is the way I'm capturing the event

document.addEventListener('click', async function (e) {

});

它在很多情况下都很好用,但在其他情况下,点击事件永远不会被触发,而是有一个或多个焦点事件被触发.我理解当 javascript 更改某些值(例如将值设置为隐藏输入或类似内容)时,可能会触发 focusout 事件.

It works good in many cases, but there're other cases where click event never get triggered, instead there're one or more focusout events that get triggered. I understad that focusout event may be shooted when javascript changes some like setting value to an hidden input or something like that.

问题是我不明白为什么在某些情况下没有触发点击事件.我可以认为,当函数(上面显示的函数)附加到内容时,有些元素仍然没有附加到 DOM,但我不确定,也确实没有找到有关的文档.或测试它的方法.如果有人可以帮我解决这个问题,我将不胜感激

The problem is that I cannot understand why in some cases click event is not triggered. I could think that in moment when the function (the function showed above) is attached to the content there're some elements that still aren't attached to the DOM, but I'm not sure and really have not find documentation about. or a way to test it.I'll be thankfull if somebody can give me a hand with this

推荐答案

监听 click 事件的页面元素函数可以在事件上调用 preventDefault() 或 stopPropagation() 这样你的监听器就赢了没看到.

The page element function that listens to a click event can call preventDefault() or stopPropagation() on the event so your listener won't see it.

尝试在事件的第一个阶段,捕获阶段,在传播链中的第一个事件目标,window:

Try listening in the first phase of the event, the capturing phase, on the first event target in the propagation chain, window:

window.addEventListener('click', yourFunction, true);

或者对于现代浏览器:

window.addEventListener('click', yourFunction, {capture: true});

如果这一项也被取消,您将不得不执行以下两项操作中的一项或两项:

If this one gets canceled as well, you'll have to do one or both of these two things:

  1. 使用 "run_at": "document_start"
  2. 监听mousedown事件

这篇关于确保内容脚本可以看到 `click` 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:36