Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

javascript - How to listen to custom events on all windows, bubbling issue?

I'm trying to listen to custom event 'peakAhBoo' so I add the event listener to gBrowser and if no gBrowser is present then I add it to aDOMWindow (gist).

Code snippet:

loadIntoWindow: function (aDOMWindow, aXULWindow) {
  if (!aDOMWindow) {
    return;
  }
  if (aDOMWindow.gBrowser) {
    aDOMWindow.gBrowser.addEventListener('peakAhBoo', respondToCustomEvent_peakAhBoo, true);
  } else {
    aDOMWindow.addEventListener('peakAhBoo', respondToCustomEvent_peakAhBoo, true);
  }
},

Code to dispatch event:

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

However if I open scratchpad and run this create/dispatch event code from environment content, its not bubbling up to gBrowser. If I run it in browser environment it never hits the window.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

ok, now i see what you mean, but according to MDN you need to use this:

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

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

I tested it and it works!

web page:

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

and in privileged code:

function respondToCustomEvent_peakAhBoo(e){
    console.log('g: '+e.target);
}

gBrowser.addEventListener("peakAhBoo", respondToCustomEvent_peakAhBoo, false, true);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...