Custom event addEventListener not working when extending EventTarget class in Greasemonkey script

355 Views Asked by At

This script works when pasted in a developer console under FireFox, but does not work when run as a Greasemonkey script, and I'm not entirely sure why. There was no documentation or much discussion around "extends EventTarget" and "dispatchEvent." But it appears that I can't listen to custom events. Any idea why or how to fix it?

// ==UserScript==
// @name     EventTarget test
// @version  1
// @grant    none
// ==/UserScript==

class evtest extends EventTarget {
    constructor() {
        super();

        console.warn( "CONSTRUCTOR OK" ); // works in GM

        var event = new CustomEvent("test_event", {
            detail: { value: 3.4, lever: false }
        });

        setTimeout(() => {
            console.warn( "DISPATCHING EVENT" ); // works in GM
            this.dispatchEvent( event );
        }, 1000);
    }
}

var test = new evtest();

test.addEventListener("test_event", (e) => {
    console.warn( "RECEIVED EVENT", e.detail ); // does NOT work in GM
});

When run in GM 4.3, the constructor runs, it dispatches the event but does not receive it. On console, it does all three things.

1

There are 1 best solutions below

0
On

Greasemonkey runs inside a sandbox, and I suppose this is why you are unable to capture the event.

Try extending window.EventTarget - this worked for me, although I am yet to figure out why.

It seems like EventTarget and window.EventTarget within the script are different functions. (You can verify this easily with a console.log(EventTarget == window.EventTarget) line in your script).