如何在所有窗口上收听自定义事件,冒泡问题?

时间:2014-03-01 23:10:43

标签: javascript-events firefox-addon listener event-bubbling custom-events

我正在尝试收听自定义事件'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。如果我在浏览器环境中运行它,它永远不会出现在窗口中。

1 个答案:

答案 0 :(得分:1)

好吧,现在我明白了你的意思,但根据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

来源:https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Interaction_between_privileged_and_non-privileged_pages

我测试了它并且它有效!

网页:

<!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);