diff --git a/src/scriptlets/dispatch-event.ts b/src/scriptlets/dispatch-event.ts index 8bbef81b..2c451ae8 100644 --- a/src/scriptlets/dispatch-event.ts +++ b/src/scriptlets/dispatch-event.ts @@ -14,7 +14,7 @@ import { * ``` * * - `event` — required, name of the event to dispatch - * - `element` — optional, CSS selector of the element to dispatch the event on + * - `element` — optional, CSS selector of the element or a window object to dispatch the event on * if not set then "document" is used * * ### Examples @@ -31,6 +31,12 @@ import { * example.org#%#//scriptlet('dispatch-event', 'test-event', '.test') * ``` * + * 3. Dispatches a custom event "window-event" on the window object. + * + * ```adblock + * example.org#%#//scriptlet('dispatch-event', 'window-event', 'window') + * ``` + * * @added unknown. */ @@ -49,23 +55,32 @@ export function dispatchEvent( const dispatch = () => { const customEvent = new Event(event); - const el = element ? document.querySelector(element) : document; + + let elToDispatch; + if (element === 'window') { + elToDispatch = window; + } else if (element) { + elToDispatch = document.querySelector(element); + } else { + elToDispatch = document; + } + const isEventAdded = listOfEvents.has(event); - if (!eventDispatched && isEventAdded && el) { + if (!eventDispatched && isEventAdded && elToDispatch) { eventDispatched = true; hit(source); - el.dispatchEvent(customEvent); + elToDispatch.dispatchEvent(customEvent); } }; - // Mock addEventListener to check if specified event has been added const wrapper = ( target: typeof EventTarget.prototype.addEventListener, thisArg: Element, args: string[], ) => { - if (thisArg && args[0]) { - listOfEvents.add(args[0]); + const eventName = args[0]; + if (thisArg && eventName) { + listOfEvents.add(eventName); setTimeout(() => { dispatch(); }, 1); diff --git a/tests/scriptlets/dispatch-event.test.js b/tests/scriptlets/dispatch-event.test.js index b0de029b..409218f1 100644 --- a/tests/scriptlets/dispatch-event.test.js +++ b/tests/scriptlets/dispatch-event.test.js @@ -78,3 +78,26 @@ test('Dispatch event - specific element', (assert) => { done(); }, 10); }); + +test('Dispatch event - window object', (assert) => { + const event = 'windowObj'; + const selector = 'window'; + + let eventFired = false; + + const scriptletArgs = [event, selector]; + runScriptlet(name, scriptletArgs); + + assert.strictEqual(eventFired, false, 'Event not fired yet'); + + window.addEventListener('windowObj', () => { + eventFired = true; + }); + + const done = assert.async(); + setTimeout(() => { + assert.strictEqual(eventFired, true, 'Event fired'); + assert.strictEqual(window.hit, 'FIRED'); + done(); + }, 10); +});