summaryrefslogtreecommitdiffstats
path: root/browser/extensions/webcompat/shims/adsafeprotected-ima.js
blob: de273de7d8f0503a9e5a83d42902c8d1f1bb21cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

/**
 * Bug 1508639 - Shim Ad Safe Protected's Google IMA adapter
 */

if (!window.googleImaVansAdapter) {
  const shimId = "AdSafeProtectedGoogleIMAAdapter";

  const sendMessageToAddon = (function() {
    const pendingMessages = new Map();
    const channel = new MessageChannel();
    channel.port1.onerror = console.error;
    channel.port1.onmessage = event => {
      const { messageId, response } = event.data;
      const resolve = pendingMessages.get(messageId);
      if (resolve) {
        pendingMessages.delete(messageId);
        resolve(response);
      }
    };
    function reconnect() {
      const detail = {
        pendingMessages: [...pendingMessages.values()],
        port: channel.port2,
        shimId,
      };
      window.dispatchEvent(new CustomEvent("ShimConnects", { detail }));
    }
    window.addEventListener("ShimHelperReady", reconnect);
    reconnect();
    return function(message) {
      const messageId =
        Math.random()
          .toString(36)
          .substring(2) + Date.now().toString(36);
      return new Promise(resolve => {
        const payload = {
          message,
          messageId,
          shimId,
        };
        pendingMessages.set(messageId, resolve);
        channel.port1.postMessage(payload);
      });
    };
  })();

  window.googleImaVansAdapter = {
    init: () => {},
    dispose: () => {},
  };

  // Treat it as an opt-in when the user clicks on a video
  // TODO: Improve this! It races to tell the bg script to unblock the ad from
  // https://pubads.g.doubleclick.net/gampad/ads before the page loads them.
  async function click(e) {
    if (e.isTrusted && e.target.closest("#video-player")) {
      document.documentElement.removeEventListener("click", click, true);
      await sendMessageToAddon("optIn");
      // TODO: reload ima3.js?
    }
  }
  document.documentElement.addEventListener("click", click, true);
}