-
Notifications
You must be signed in to change notification settings - Fork 2
/
background.js
80 lines (67 loc) · 1.66 KB
/
background.js
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
const SPOTIFY_URL = "open.spotify.com/";
const SPOTIFY_AD_TITLE = "Spotify – Advertisement";
const random = (arr) => {
return arr[Math.floor(Math.random() * arr.length)];
};
class MusicPlayer {
constructor() {
this.currentlyPlaying = null;
}
audioUrls = [
"music/ThinkingFree.mp3",
"music/RockHopping.mp3",
"music/Cheeky.mp3",
"music/HereForYears.mp3",
"music/lofi-study.mp3",
];
playRandom() {
const audioPath = random(this.audioUrls);
const audio = new Audio(audioPath);
audio.volume = 0.8;
this.currentlyPlaying = audio;
audio.play();
}
stop() {
if (this.currentlyPlaying) {
this.currentlyPlaying.pause();
this.currentlyPlaying = null;
}
}
}
const fillerMusic = new MusicPlayer();
const titleIsAd = (title) => {
const adRegex = new RegExp(`^${SPOTIFY_AD_TITLE}`);
return !!title.match(adRegex);
};
const mute = (tabId) => {
chrome.tabs.update(tabId, { muted: true });
};
const unmute = (tabId) => {
chrome.tabs.update(tabId, { muted: false });
};
// create a blank tab for launching play of bg music without being muted
const playFillerInNewTab = () => {
chrome.tabs.create({ url: "", active: false }, (tab) => {
fillerMusic.playRandom();
chrome.tabs.remove(tab.id);
});
};
const checkForAd = (tabId, _changeInfo, tab) => {
if (tab.url.match(SPOTIFY_URL)) {
if (titleIsAd(tab.title)) {
if (!tab.mutedInfo.muted) {
mute(tabId);
playFillerInNewTab();
}
} else {
if (tab.mutedInfo.muted) {
unmute(tabId);
}
fillerMusic.stop();
}
}
};
const run = () => {
chrome.tabs.onUpdated.addListener(checkForAd);
};
run();