-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (80 loc) · 2.3 KB
/
index.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
81
82
83
84
85
86
87
88
89
90
(function() {
// global object
const changeIcon = {
actions : [],
onAnotherTab: function(title,icon) {
if(!title || !icon) return;
window.addEventListener("blur", () => {
opt.mainTitle.innerText = title;
addNewFavicons(icon);
});
},
onThisTab: function(cb) {
window.addEventListener("focus", () => {
if(!cb) return emitAction("original");
cb();
});
},
addAction: addAction,
emitAction: emitAction
};
// private options
const opt = {};
// private functions
function getInitialOpt() {
// get title
const mainTitle = document.getElementsByTagName("title")[0];
// get favicon in all links [ rel = icon ]
const links = document.getElementsByTagName("link");
const mainFavicons = [];
// loop the links to find icon
for(let i = 0; i < links.length; i++) {
if(links[i].rel === "icon") mainFavicons.push(links[i]);
}
// add standart action for turning to original
addAction("original",mainTitle.innerText,mainFavicons[0].href);
opt.mainTitle = mainTitle;
opt.favicons = mainFavicons;
}
function addNewFavicons(icon) {
//-> Changing the favicons source (href) is unsiffcent have to remove all of them and create new ones
const head = document.getElementsByTagName("head")[0];
for(let i = 0; i < head.children.length; i++) {
const child = head.children[i];
if(child.rel && child.rel === "icon") {
head.removeChild(child);
}
}
//-> Old ones have removed
for(let i = 0; i < opt.favicons.length; i++) {
const favicon = opt.favicons[i];
favicon.href = icon
head.appendChild(favicon);
}
}
function addAction(name,title,icon) {
if(!name || !title || !icon) throw "provide values";
// check for other actions with same name
if(changeIcon.actions.find(action => action.name === name)) throw name + " was used before";
// push the new action
changeIcon.actions.push({
name,
title,
icon
});
}
function emitAction(name) {
// find the action with given name
const action = changeIcon.actions.find(action => {
return name === action.name;
});
// return if not found
if(!action) throw name + " was not found";
// setup options
opt.mainTitle.innerText = action.title;
// delete all existing favicons and and new ones
addNewFavicons(action.icon);
}
getInitialOpt();
window.changeIcon = changeIcon;
})();