javascript – 如何在所有窗口上收听自定义事件,冒泡问题?
作者:互联网
我正在尝试收听自定义事件’peakAhBoo’,因此我将事件监听器添加到gBrowser中,如果没有gBrowser,则将其添加到aDOMWindow(gist).
代码段:
loadIntoWindow: function (aDOMWindow, aXULWindow) {
if (!aDOMWindow) {
return;
}
if (aDOMWindow.gBrowser) {
aDOMWindow.gBrowser.addEventListener('peakAhBoo', respondToCustomEvent_peakAhBoo, true);
} else {
aDOMWindow.addEventListener('peakAhBoo', respondToCustomEvent_peakAhBoo, true);
}
},
发送事件的代码:
var myEvent = new CustomEvent('peakAhBoo', {
'detail': {
'hazcheeseburger': true
}
});
var myEvent = window.document.createEvent('CustomEvent');
var myEventDetail = {hello:'world'};
myEvent.initCustomEvent('peakAhBoo', true, true, myEventDetail);
window.dispatchEvent(myEvent);
但是,如果我打开暂存器并从环境内容运行此创建/调度事件代码,它不会冒泡到gBrowser.如果我在浏览器环境中运行它,它永远不会到达窗口.
解决方法:
好的,现在我明白了你的意思,但根据MDN,你需要使用这个:
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true);
// The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event
我测试了它,它的工作原理!
网页:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="main-content"><button onclick="trigger()">Trigger custom event</button></div>
<script type="text/javascript">
function trigger(){
var myEvent = new CustomEvent('peakAhBoo', {
'detail': {
'hazcheeseburger': true
}
});
var myEvent = window.document.createEvent('CustomEvent');
var myEventDetail = {hello:'world'};
myEvent.initCustomEvent('peakAhBoo', true, true, myEventDetail);
window.dispatchEvent(myEvent);
console.log(myEvent)
}
</script>
</body>
</html>
并在特权代码中:
function respondToCustomEvent_peakAhBoo(e){
console.log('g: '+e.target);
}
gBrowser.addEventListener("peakAhBoo", respondToCustomEvent_peakAhBoo, false, true);
标签:event-bubbling,javascript,listener,firefox-addon,dom-events 来源: https://codeday.me/bug/20191002/1844283.html