我有一个 Chrome 扩展程序需要产生类似人类的鼠标和键盘行为(具体来说,生成具有 isTrusted
值 true
的事件)。除了使用 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 usingdispatchEvent()
). The sole legacy exception isclick()
, which causes the user agent to dispatch an event whoseisTrusted
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 theinitEvent()
method, or dispatched via thedispatchEvent()
method. TheisTrusted
attribute of trusted events has a value oftrue
, while untrusted events have aisTrusted
attribute value offalse
.
因此,isTrusted
仅反射(reflect)事件是否已使用 createEvent
人工调度或创建, initEvent
, 或 dispatchEvent
.现在,看看 Window.scroll
的定义根据 CSSOM View Module Editor's Draft :
When the
scroll()
method is invoked these steps must be run:[...]
- 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/