Bri*_*fer 10 javascript javascript-events
我有一个Chrome扩展程序需要产生类似人类的鼠标和键盘行为(具体来说,生成具有isTrusted值的事件true).除了滚动chrome.debuggerAPI 之外,我可以做我需要的一切.
但似乎该Window.scroll()方法足以达到Chrome 52和Firefox 48.0a1的目的.通过将事件侦听器附加到页面可以观察到这一点,如下所示:
document.addEventListener("scroll", function (event) {
console.log("event trusted? " + event.isTrusted);
});
Run Code Online (Sandbox Code Playgroud)
然后window.scroll(0, 10);在开发者控制台中运行类似的东西.这将登录event trusted? true到开发人员控制台.
我的问题是:为什么会这样?由于滚动事件是由脚本明确生成的,因此isTrusted属性不应该是false这种情况吗?
这符合DOM生活标准的规范:
注意:
isTrusted是一个方便的,指示一个是否事件被分派由用户代理(而不是使用dispatchEvent()).唯一的遗留异常是click(),导致用户代理将其属性初始化为false 的事件分派isTrusted.
此外,在DOM Level 3事件规范中:
3.4.值得信赖的事件
由用户代理生成的事件,或者作为用户交互的结果,或者作为DOM更改的直接结果,由用户代理信任具有权限的事件
createEvent()initEvent()dispatchEvent(),这些权限不是由脚本通过该方法生成的事件,已修改使用该方法,或通过该方法调度.isTrusted可信事件的属性值为true,而不可信事件的isTrusted属性值为false.
因此,isTrusted只有反映如果事件已派出或创建人为使用createEvent,initEvent或dispatchEvent.现在,看看定义Window.scroll每CSSOM查看模块编辑的草案:
scroll()调用该方法时,必须运行以下步骤:[...]
- 如果使用两个参数调用,请遵循以下子步骤:
[...]
12. 执行视口滚动到位置,文档的根元素作为关联元素(如果有),否则为null,滚动行为是选项的
behavior字典成员的值.
无处在该方法与创建的人造事件createEvent,initEvent或dispatchEvent,由此值isTrusted是true.请注意,使用Window.scroll仍会触发事件处理程序,因为它与事件循环集成,并在scroll滚动视口或元素时发出事件.这不,但是,使用createEvent,initEvent或dispatchEvent.
使用该isTrusted事件不是检测脚本是否生成事件的可靠方法.它只有当事件已创建并与派出检测createEvent,initEvent或dispatchEvent.
似乎*.scroll或更改scrollTop属性无法正确构造事件。正如您在示例中看到的,isTrusted如果false我自己创建事件。我认为这是引擎中的一个错误
"use strict";
var event = new Event('scroll');
//target.addEventListener(type, listener[, options]);
//target.addEventListener(type, listener[, useCapture]);
//target.addEventListener(type, listener[, useCapture, wantsUntrusted ]); // Gecko/Mozilla only
window.addEventListener('scroll', function(e) {
console.log(e.isTrusted);
}, false);
console.log('JS engine event:');
window.scroll(10, 10);
setTimeout(function() {
console.log('Selfmade event:');
window.dispatchEvent(event);
}, 1000);
setTimeout(function() {
console.log('Another event triggered by changing the scrollTop property:');
window.scrollTop = '20px';
}, 2000);Run Code Online (Sandbox Code Playgroud)
#container {
width: 100px;
height: 10000px;
overflow: scroll;
}Run Code Online (Sandbox Code Playgroud)
<div id="container">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>Run Code Online (Sandbox Code Playgroud)