File size: 1,570 Bytes
b59aa07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
let originalTitle = "";
let titleInterval: number | undefined;

const isBrowser =
  typeof window !== "undefined" && typeof document !== "undefined";

// Use a constant for the notification parameter to avoid hardcoded strings
const NOTIFICATION_PARAM = "notification";

export const browserTab = {
  startNotification(message: string) {
    if (!isBrowser) return;

    // Store original title if not already stored
    if (!originalTitle) {
      originalTitle = document.title;
    }

    // Clear any existing interval
    if (titleInterval) {
      this.stopNotification();
    }

    // Alternate between original title and notification message
    titleInterval = window.setInterval(() => {
      document.title =
        document.title === originalTitle ? message : originalTitle;
    }, 1000);

    // Set favicon to indicate notification
    const favicon = document.querySelector(
      'link[rel="icon"]',
    ) as HTMLLinkElement;
    if (favicon) {
      favicon.href = favicon.href.includes(`?${NOTIFICATION_PARAM}`)
        ? favicon.href
        : `${favicon.href}?${NOTIFICATION_PARAM}`;
    }
  },

  stopNotification() {
    if (!isBrowser) return;

    if (titleInterval) {
      window.clearInterval(titleInterval);
      titleInterval = undefined;
    }
    if (originalTitle) {
      document.title = originalTitle;
    }

    // Reset favicon
    const favicon = document.querySelector(
      'link[rel="icon"]',
    ) as HTMLLinkElement;
    if (favicon) {
      favicon.href = favicon.href.replace(`?${NOTIFICATION_PARAM}`, "");
    }
  },
};