javascript - 为什么调用 Window.scroll() 会产生可信事件?

标签 javascript dom-events

我有一个 Chrome 扩展程序需要产生类似人类的鼠标和键盘行为(具体来说,生成具有 isTrustedtrue 的事件)。除了使用 chrome.debugger API 滚动之外,我可以做我需要的一切。

但对于 Chrome 52 和 Firefox 48.0a1 而言,Window.scroll() 方法似乎足以满足此目的。这可以通过将事件监听器附加到页面来观察,如下所示:

document.addEventListener("scroll", function (event) { 
    console.log("event trusted? " + event.isTrusted);
});

然后在开发人员控制台中运行类似 window.scroll(0, 10); 的代码。这将记录 事件可信吗?对开发者控制台是正确的

我的问题是:为什么会这样?在这种情况下,isTrusted 属性不应该是 false 因为滚动事件显然是由脚本生成的吗?

最佳答案

这是根据规范,根据 DOM Living Standard :

NOTE: isTrusted is a convenience that indicates whether an event is dispatched by the user agent (as opposed to using dispatchEvent()). The sole legacy exception is click(), which causes the user agent to dispatch an event whose isTrusted attribute is initialized to false.

另外,在 DOM Level 3 Events Specification :

3.4. Trusted events

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the createEvent() method, modified using the initEvent() method, or dispatched via the dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

因此,isTrusted仅反射(reflect)事件是否已使用 createEvent 人工调度或创建, initEvent , 或 dispatchEvent .现在,看看 Window.scroll 的定义根据 CSSOM View Module Editor's Draft :

When the scroll() method is invoked these steps must be run:

[...]

  1. If invoked with two arguments, follow these substeps:

     [...]

     12. Perform a scroll of the viewport to position, document’s root element as the associated element, if there is one, or null otherwise, and the scroll behavior being the value of the behavior dictionary member of options.

方法中没有任何地方是使用 createEvent 创建的人工事件, initEvent , 或 dispatchEvent ,因此 isTrusted 的值是true .请注意,使用 Window.scroll仍然触发事件处理程序,因为它与事件循环集成,并且 scroll滚动视口(viewport)或元素时发出事件。然而,这使用createEvent , initEvent , 或 dispatchEvent .

使用 isTrusted事件不是检测脚本是否生成事件的可靠方法。它仅检测是否已使用 createEvent 创建和调度事件, initEvent , 或 dispatchEvent .

关于javascript - 为什么调用 Window.scroll() 会产生可信事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36656858/

相关文章:

javascript - 使用来自外部 API 的传单解析 GeoJSON

javascript - 使滚动键滚动正确的页面元素

javascript - 使用javascript压缩二维数组的重复

javascript - 如何根据下拉菜单隐藏输入

javascript - 将值从数组传递给 React Native 中的函数

webpack - Babel 和 EventTarget 的子类

javascript - AngularJS 在范围内从 addEventListener 返回值

javascript - 使用多个括号在 Javascript 中关闭

javascript - 从数组中设置 fullcalendar 中的事件

javascript - addEventListener 中的 Event 对象如果没有传入回调,从哪里来?