-
Notifications
You must be signed in to change notification settings - Fork 0
/
redirect-to-cache.js
91 lines (67 loc) · 2.35 KB
/
redirect-to-cache.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
91
const KEY_REDIRECT = "neurowhai-OTAC-redirect";
let flagRedirect = true;
function setRedirectFlag(flag) {
flagRedirect = flag;
chrome.browserAction.setBadgeText({ text: (flag ? "ON" : "OFF") });
chrome.browserAction.setBadgeBackgroundColor({
color: (flag ? [66, 133, 244, 200] : [112, 146, 190, 200])
});
}
// Get first data
chrome.storage.local.get(KEY_REDIRECT, function(items) {
var data = items[KEY_REDIRECT];
setRedirectFlag(data != "0");
})
// Change flag
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.storage.local.get(KEY_REDIRECT, function(items) {
var data = items[KEY_REDIRECT];
setRedirectFlag(data == "0");
var newData = {};
newData[KEY_REDIRECT] = (flagRedirect ? "1" : "0");
chrome.storage.local.set(newData);
})
});
function redirect(tabId, url) {
chrome.tabs.update(tabId, {
url: url,
active: false
});
}
function redirectToCache(tabId, url) {
redirect(tabId, "http://webcache.googleusercontent.com/search?q=cache:" + url);
}
function redirectToWayback(tabId, url) {
url = "https://web.archive.org/save/" + url;
chrome.tabs.executeScript(tabId, {
code: "location.replace(\'" + encodeURI(url) + "\')"
});
}
function needRedirect(url) {
var matches = url.match(/^http:\/\/([\d\w\-\_]+)\.tistory\.com/);
return (matches !== null && matches[1] != 'www');
}
chrome.webNavigation.onBeforeNavigate.addListener(function(details) {
if (flagRedirect === false) {
return;
}
// If only main window navigation
if (details.frameId === 0 && needRedirect(details.url)) {
// Redirect to Google web cache
redirectToCache(details.tabId, details.url);
}
}, {
url: [{urlMatches: "^http:\\/\\/[\\d\\w\\-\\_]+\\.tistory\\.com"}]
});
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (flagRedirect === false) {
return;
}
var url = changeInfo.url || tab.url;
var title = changeInfo.title || tab.title;
var matches = url.match(/^https?:\/\/webcache\.googleusercontent\.com\/search\?q=cache:(http:\/\/[\d\w\-\_]+\.tistory\.com.*)/);
// Redirect to Archive if there is no cache
if (matches !== null && title == "Error 404 (Not Found)!!1") {
redirectToWayback(tabId, matches[1]);
}
});