summaryrefslogtreecommitdiffstats
path: root/mobile/android/android-components/components/feature/search/src/main/assets/extensions/ads/adsTelemetry.js
blob: 07787993262a1dc896c6621ca5f58d897782578a (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
70
71
72
73
74
75
76
77
78
79
80
/* 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/. */

/**
 * Send
 * - current URL
 * - cookies of this page
 * - all links found in this page
 * to the native application.
 */
function sendCurrentState() {
  let message = {
    url: document.location.href,
    urls: getLinks(),
    cookies: getCookies(),
  };
  browser.runtime.sendNativeMessage("MozacBrowserAdsMessage", message);
}

/**
 * Get all links in the current page.
 *
 * @return {Array<string>} containing all current links in the current page.
 */
function getLinks() {
  let urls = [];

  let anchors = document.getElementsByTagName("a");
  for (let anchor of anchors) {
    if (!anchor.href) {
      continue;
    }
    urls.push(anchor.href);
  }

  return urls;
}

/**
 * Get all cookies for the current document.
 *
 * @return {Array<{name: string, value: string}>} containing all cookies.
 */
function getCookies() {
  let cookiesList = document.cookie.split("; ");
  let result = [];

  cookiesList.forEach(cookie => {
    var [name, ...value] = cookie.split("=");
    // For that special cases where the value contains '='.
    value = value.join("=");

    result.push({
      name: name,
      value: value,
    });
  });

  return result;
}

// Whenever a page is first accessed or when loaded from cache
// send all needed data about the ads provider to the app.
const events = ["pageshow", "load"];
const eventLogger = event => {
  switch (event.type) {
    case "load":
      sendCurrentState();
      break;
    case "pageshow":
      if (event.persisted) {
        sendCurrentState();
      }
      break;
    default:
      console.log("Event:", event.type);
  }
};
events.forEach(eventName => window.addEventListener(eventName, eventLogger));