-
Notifications
You must be signed in to change notification settings - Fork 156
/
background.js
69 lines (64 loc) · 2.36 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
var ReResMap = [];
var typeMap = {
"txt" : "text/plain",
"html" : "text/html",
"css" : "text/css",
"js" : "text/javascript",
"json" : "text/json",
"xml" : "text/xml",
"jpg" : "image/jpeg",
"gif" : "image/gif",
"png" : "image/png",
"webp" : "image/webp"
}
function getLocalStorage() {
ReResMap = window.localStorage.ReResMap ? JSON.parse(window.localStorage.ReResMap) : ReResMap;
}
function getLocalFileUrl(url) {
var arr = url.split('.');
var type = arr[arr.length-1];
var xhr = new XMLHttpRequest();
xhr.open('get', url, false);
xhr.send(null);
var content = xhr.responseText || xhr.responseXML;
if (!content) {
return false;
}
content = encodeURIComponent(
type === 'js' ?
content.replace(/[\u0080-\uffff]/g, function($0) {
var str = $0.charCodeAt(0).toString(16);
return "\\u" + '00000'.substr(0, 4 - str.length) + str;
}) : content
);
return ("data:" + (typeMap[type] || typeMap.txt) + ";charset=utf-8," + content);
}
chrome.webRequest.onBeforeRequest.addListener(function (details) {
var url = details.url;
for (var i = 0, len = ReResMap.length; i < len; i++) {
var reg = new RegExp(ReResMap[i].req, 'gi');
if (ReResMap[i].checked && typeof ReResMap[i].res === 'string' && reg.test(url)) {
if (!/^file:\/\//.test(ReResMap[i].res)) {
// return ReResMap[i].type === 'file' ?
// {redirectUrl: ReResMap[i].res} :
// {redirectUrl: url.replace(reg, ReResMap[i].res)};
do {
url = url.replace(reg, ReResMap[i].res);
} while (reg.test(url))
} else {
// return ReResMap[i].type === 'file' ?
// {redirectUrl: getLocalFileUrl(ReResMap[i].res)} :
// {redirectUrl: getLocalFileUrl(url.replace(reg, ReResMap[i].res))};
do {
url = getLocalFileUrl(url.replace(reg, ReResMap[i].res));
} while (reg.test(url))
}
}
}
return url === details.url ? {} : { redirectUrl: url };
},
{urls: ["<all_urls>"]},
["blocking"]
);
getLocalStorage();
window.addEventListener('storage', getLocalStorage, false);