Skip to content

Commit

Permalink
Further improve google-ima shim script
Browse files Browse the repository at this point in the history
I worked through some of the websites listed in the uBlock issue[1]
for the google-ima.js surrogate script, to see what was going
wrong. It turned out the addEventListener method supports an optional
context Object, which is bound to the listener if provided. Some
websites make use of that, and then break when `this` is not bound
correctly when events are dispatched.

See also duckduckgo/tracker-surrogates#24

1 - uBlockOrigin/uBlock-issues#2265
  • Loading branch information
kzar committed Oct 25, 2023
1 parent c2217a1 commit 5508ce7
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/web_accessible_resources/google-ima.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
* - Modified to avoid jshint warnings as per uBO's config
* - Added `OmidVerificationVendor` to `ima`
* - Have `AdError.getInnerError()` return `null`
* - Have `AdDisplayContainer` constructor add DIV element to container
* - Added missing event dispatcher functionality
* - Corrected return type of `Ad.getUniversalAdIds()`
* - Corrected typo in `UniversalAdIdInfo.getAdIdValue()` method name
*
* Related issue:
* - https://github.com/uBlockOrigin/uBlock-issues/issues/2158
Expand Down Expand Up @@ -331,8 +335,9 @@ if (!window.google || !window.google.ima || !window.google.ima.VERSION) {
}

_dispatch(e) {
const listeners = this.listeners.get(e.type) || [];
for (const listener of Array.from(listeners)) {
let listeners = this.listeners.get(e.type);
listeners = listeners ? Array.from(listeners.values()) : [];
for (const listener of listeners) {
try {
listener(e);
} catch (r) {
Expand All @@ -341,16 +346,16 @@ if (!window.google || !window.google.ima || !window.google.ima.VERSION) {
}
}

addEventListener(types, c) {
addEventListener(types, c, options, context) {
if (!Array.isArray(types)) {
types = [types];
}

for (const t of types) {
if (!this.listeners.has(t)) {
this.listeners.set(t, new Set());
this.listeners.set(t, new Map());
}
this.listeners.get(t).add(c);
this.listeners.get(t).set(c, c.bind(context || this));
}
}

Expand Down

0 comments on commit 5508ce7

Please sign in to comment.