Skip to content

Commit

Permalink
Add ability to dispatch events on the window object
Browse files Browse the repository at this point in the history
  • Loading branch information
AdamWr committed Apr 5, 2024
1 parent 8007b06 commit 9382072
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
29 changes: 22 additions & 7 deletions src/scriptlets/dispatch-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
*/

Expand All @@ -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);
Expand Down
23 changes: 23 additions & 0 deletions tests/scriptlets/dispatch-event.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

0 comments on commit 9382072

Please sign in to comment.