我正在尝试收听自定义事件'peakAhBoo',因此我将事件监听器添加到gBrowser
,如果没有gBrowser
,则将其添加到aDOMWindow
({{ 3}})。
代码段:
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
。如果我在浏览器环境中运行它,它永远不会出现在窗口中。
答案 0 :(得分:1)
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);