-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
164 lines (139 loc) · 5.27 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// prerender.cloud chrome extension - for prerendering javascript pages on a remote server to allow javascriptless clients
/**
* 1. disable javascript
* 2. let the browser navigate to a page normally
* 2a. Q: why bother with a normal request if we're replacing it with a prerendered copy?
* A: because the prerenderd HTML often has relative URLs, so we want our base URL to be
* the original URL so the images can be served (as opposed to the service.prerender.cloud URL)
* alternatively, we could load a light-weight fake, e.g. example.org, and just rewrite/redirect all incoming
* chrome.webRequest's, but then the URL bar shows the incorrect URL
* 3. immediately start an AJAX request, within the context of the extension
* 3. start a loop that replaces any normal content with 'loading'
* 4. wait for the normal navigation to fire onDOMContentLoaded
* 4. use "message passing" to send the AJAX response to the client window
* 5. stop the 'loading' loop when the prerendered version is received from "message passing"
* 6. finally set the DOM innerHTML
*/
var tabSubscribers;
class TabSubscribers {
create(tabId, url) {
this[tabId] = new Tab(tabId, url)
}
remove(tabId) {
delete this[tabId];
}
}
function isOn() { return localStorage.getItem('toggle') === 'true'; }
function toggle(isOn) {
chrome.browserAction.setBadgeText({text: isOn ? 'on' : 'off'});
chrome.contentSettings.javascript.set({primaryPattern: '<all_urls>', setting: isOn ? 'block' : 'allow'});
tabSubscribers = new TabSubscribers();
}
// subscribe to the browser_action (popup window) toggle button
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(({ isOn }) => toggle(isOn));
});
// read from local storage to see what to do on initial boot
toggle(isOn());
function runCode(tabId, code, cb) {
chrome.tabs.executeScript(tabId, {code: code, runAt: 'document_start'}, cb);
}
function addListenerCode() {
return `
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
window.prerendered = true;
document.documentElement.innerHTML=request.prerendered;
});
`;
}
function prerenderFetch(apiKey, url) {
return new Promise(function(res, rej) {
var request = new Request('https://service.prerender.cloud/'+url, {
headers: {'x-prerender-token': `${apiKey}`}
});
window.fetch(request)
.then(res => res.text())
.then(res)
.catch(rej)
})
}
function loadingCode() {
return `
var clearContent = function() {
if (!window.prerendered) {
document.documentElement.innerHTML='loading prerendered version...';
window.requestAnimationFrame(clearContent);
}
}
window.requestAnimationFrame(clearContent);
`;
}
class Tab {
constructor(tabId, url) {
this.tabId = tabId;
this.url = url;
this._startLoad();
this._startFetch();
}
onBeforeSendHeaders(details) {
this._startLoad();
}
onHeadersReceived() {
this._startLoad();
}
onResponseStarted(details) {
this._startLoad();
}
onDOMContentLoaded(details) {
this._startLoad();
this._startListener();
if (this.prerendered) {
chrome.tabs.sendMessage(this.tabId, { prerendered: this.prerendered });
} else {
this.loaded = true;
}
}
_startLoad() {
runCode(this.tabId, loadingCode());
}
_startFetch() {
chrome.storage.sync.get({apiKey: ''}, items => {
prerenderFetch(items.apiKey, this.url)
.then(prerendered => {
if (this.loaded) {
chrome.tabs.sendMessage(this.tabId, { prerendered });
} else {
this.prerendered = prerendered;
}
})
});
}
_startListener() {
runCode(this.tabId, addListenerCode())
}
}
// subscribe to all request's rendering/painting lifecycle per tab
chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
isOn() && tabSubscribers[details.tabId] && tabSubscribers[details.tabId].onBeforeSendHeaders(details);
}, {urls: ['<all_urls>'], types: ['main_frame']});
chrome.webRequest.onHeadersReceived.addListener(function(details) {
isOn() && tabSubscribers[details.tabId] && tabSubscribers[details.tabId].onHeadersReceived(details);
}, {urls: ['<all_urls>'], types: ['main_frame']});
chrome.webRequest.onResponseStarted.addListener(function(details) {
isOn() && tabSubscribers[details.tabId] && tabSubscribers[details.tabId].onResponseStarted(details);
}, {urls: ['<all_urls>'], types: ['main_frame']});
chrome.webNavigation.onDOMContentLoaded.addListener(function(details) {
isOn() && tabSubscribers[details.tabId] && tabSubscribers[details.tabId].onDOMContentLoaded(details);
});
// create Tab objects per request/response start stop lifecycle
chrome.webRequest.onBeforeRequest.addListener(function(details) {
if (!isOn()) return;
// prevents chrome://, (extensions, options pages etc.. from triggering the prerender)
if (!details.url.startsWith('http')) return;
tabSubscribers.remove(details.tabId);
tabSubscribers.create(details.tabId, details.url);
}, {urls: ['<all_urls>'], types: ['main_frame']}, ['blocking']);
chrome.webNavigation.onCompleted.addListener(function(details) {
tabSubscribers.remove(details.tabId);
}, {urls: ['<all_urls>'], types: ['main_frame']}, ['blocking']);