-
Notifications
You must be signed in to change notification settings - Fork 10
/
background.js
70 lines (60 loc) · 1.71 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
let DEFAULT_UA = navigator.userAgent;
let CUSTOM_UA = DEFAULT_UA;
function init() {
bindOnBeforeSendHeaders();
bindOnMessage();
}
function onBeforeSendHeadersCallback(details) {
if (CUSTOM_UA === DEFAULT_UA) {
return;
}
for (let i = 0; i < details.requestHeaders.length; i++) {
if (details.requestHeaders[i].name !== 'User-Agent') {
continue;
}
details.requestHeaders[i].value = CUSTOM_UA;
break;
}
return {
requestHeaders: details.requestHeaders
};
}
function bindOnBeforeSendHeaders() {
chrome.webRequest.onBeforeSendHeaders.addListener(
onBeforeSendHeadersCallback,
{ urls: ["<all_urls>"] },
["blocking", "requestHeaders"]
);
}
function bindOnMessage() {
chrome.runtime.onMessage.addListener(function(msg, sender, callback) {
if (msg.type === 'getUA') {
callback(CUSTOM_UA);
} else if (msg.type === 'setUA') {
gotMessageSetUA(msg.ua);
} else if (msg.type === 'resetUA') {
gotMessageResetUA();
}
});
}
function gotMessageSetUA(ua) {
if (ua === '') {
CUSTOM_UA = DEFAULT_UA;
} else if(isValidUA(ua)) {
CUSTOM_UA = ua;
} else {
throw "Invalid UA";
}
}
function gotMessageResetUA() {
CUSTOM_UA = DEFAULT_UA;
}
function isValidUA(ua) {
// Pretty much any string is considered valid.
// Invalid if not a string, or has new line characters.
return isString(ua) && !ua.match("[\n\r]") ? true : false;
}
function isString(input) {
return input !== undefined && input !== null && typeof(input) === 'string';
}
init();