about summary refs log tree commit diff stats
path: root/src/assets/javascripts/remove-twitter-sw.js
blob: 13e8ee0b9b22b5b7290fe34f431619a2a422b27a (plain) (blame)
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
"use strict";

let disableTwitter;
let nitterInstance;
let redirectBypassFlag;
let exceptions;

window.browser = window.browser || window.chrome;

Promise.all([
  import(browser.runtime.getURL("src/assets/javascripts/helpers/common.js")),
  import(browser.runtime.getURL("src/assets/javascripts/helpers/twitter.js")),
]).then(
  (helpers) => {
    let commonHelper;
    let twitterHelper;
    [commonHelper, twitterHelper] = helpers;

    function shouldRedirect(url) {
      return (
        !redirectBypassFlag &&
        !disableTwitter &&
        url.host !== nitterInstance &&
        !url.pathname.includes("/home")
      );
    }

    function redirectTwitter(url) {
      if (url.host.split(".")[0] === "pbs")
        return `${nitterInstance}/pic/${encodeURIComponent(url.href)}`;
      else if (url.host.split(".")[0] === "video")
        return `${nitterInstance}/gif/${encodeURIComponent(url.href)}`;
      else
        return `${nitterInstance}${url.pathname}${url.search}`;
    }

    browser.storage.sync.get(
      [
        "nitterInstance",
        "disableTwitter",
        "removeTwitterSW",
        "redirectBypassFlag",
        "exceptions",
      ],
      (result) => {
        redirectBypassFlag = result.redirectBypassFlag;
        browser.storage.sync.set({ redirectBypassFlag: false });
        if (!result.removeTwitterSW) {
          disableTwitter = result.disableTwitter;
          nitterInstance = result.nitterInstance ?? commonHelper.default.getRandomInstance(twitterHelper.default.redirects);
          exceptions = result.exceptions ? result.exceptions.map((e) => new RegExp(e)) : [];
          navigator.serviceWorker.getRegistrations().then((registrations) => {
            for (let registration of registrations) {
              if (registration.scope === "https://twitter.com/") {
                registration.unregister();
                console.log("Unregistered Twitter SW", registration);
              }
            }
          });
          const url = new URL(window.location);
          if (shouldRedirect(url)) {
            const redirect = redirectTwitter(url);
            console.info("Redirecting", `"${url.href}"`, "=>", `"${redirect}"`);
            window.location = redirect;
          }
        }
      }
    );
  },
  (error) => {
    console.error(error);
  }
);