-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.js
85 lines (74 loc) · 2.1 KB
/
request.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
var
rules,
lastRequestId;
if(localStorage['rules']){
rules = JSON.parse(localStorage['rules']);
}
else{
rules = [];
}
chrome.webRequest.onBeforeRequest.addListener(function(details) {
return redirectToMatchingRule(details);
}, {
urls : ["<all_urls>"]
}, ["blocking"]);
function redirectToMatchingRule(details) {
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (rule.isActive && details.url.indexOf(rule.from) > -1 && details.requestId !== lastRequestId ) {
lastRequestId = details.requestId;
var re = /\s*,\s*/;
var urlList = rule.to.split(re);
urlList.push(rule.from);
var randomIndex = Math.floor(Math.random()*urlList.length);
var urlTo = urlList[randomIndex];
return{
redirectUrl : details.url.replace(rule.from, urlTo)
};
}
}
}
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if ( typeof request.rule !== 'undefined') {
rules.push(request.rule);
updateLocalStorage(rules);
sendResponse({
rules : this.rules
});
} else if ( typeof request.removeAllRules !== 'undefined') {
rules = [];
updateLocalStorage(rules)
sendResponse({
rules : this.rules
});
} else if ( typeof request.getRules !== 'undefined') {
sendResponse({
rules : this.rules
});
} else if ( typeof request.toggleIndex !== 'undefined') {
rules[request.toggleIndex].isActive = !rules[request.toggleIndex].isActive;
updateLocalStorage(rules);
sendResponse({
rules : this.rules
});
} else if ( typeof request.editIndex !== 'undefined') {
rules[request.editIndex] = request.updatedRule;
updateLocalStorage(rules);
sendResponse({
rules : this.rules
});
} else if ( typeof request.removeIndex !== 'undefined') {
rules.splice(request.removeIndex, 1);
updateLocalStorage(rules);
sendResponse({
rules : this.rules
});
} else if ( typeof request.getIndex !== 'undefined') {
sendResponse({
rule : rules[request.getIndex]
});
}
});
function updateLocalStorage(rules){
localStorage['rules'] = JSON.stringify(rules);
}