-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
page.ts
221 lines (204 loc) · 7.46 KB
/
page.ts
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import findChannelFromTwitchTvUrl from "../common/ts/findChannelFromTwitchTvUrl";
import toAbsoluteUrl from "../common/ts/toAbsoluteUrl";
import { MessageType } from "../types";
import { getFetch } from "./getFetch";
import {
getSendMessageToContentScript,
getSendMessageToContentScriptAndWaitForResponse,
getSendMessageToPageScript,
getSendMessageToPageScriptAndWaitForResponse,
getSendMessageToWorkerScripts,
getSendMessageToWorkerScriptsAndWaitForResponse,
} from "./sendMessage";
import type { PageState } from "./types";
console.info("[TTV LOL PRO] Page script running.");
const params = JSON.parse(document.currentScript!.dataset.params!);
const sendMessageToContentScript = getSendMessageToContentScript();
const sendMessageToContentScriptAndWaitForResponse =
getSendMessageToContentScriptAndWaitForResponse();
const sendMessageToPageScript = getSendMessageToPageScript();
const sendMessageToPageScriptAndWaitForResponse =
getSendMessageToPageScriptAndWaitForResponse();
const sendMessageToWorkerScripts = getSendMessageToWorkerScripts();
const sendMessageToWorkerScriptsAndWaitForResponse =
getSendMessageToWorkerScriptsAndWaitForResponse();
const pageState: PageState = {
isChromium: params.isChromium,
scope: "page",
state: undefined,
twitchWorkers: [],
sendMessageToContentScript,
sendMessageToContentScriptAndWaitForResponse,
sendMessageToPageScript,
sendMessageToPageScriptAndWaitForResponse,
sendMessageToWorkerScripts,
sendMessageToWorkerScriptsAndWaitForResponse,
};
window.fetch = getFetch(pageState);
window.Worker = class Worker extends window.Worker {
constructor(scriptURL: string | URL, options?: WorkerOptions) {
const fullUrl = toAbsoluteUrl(scriptURL.toString());
const isTwitchWorker = fullUrl.includes(".twitch.tv");
if (!isTwitchWorker) {
super(scriptURL, options);
return;
}
let script = "";
// Fetch Twitch's script, since Firefox Nightly errors out when trying to
// import a blob URL directly.
const xhr = new XMLHttpRequest();
xhr.open("GET", fullUrl, false);
xhr.send();
if (200 <= xhr.status && xhr.status < 300) {
script = xhr.responseText;
} else {
console.warn(`[TTV LOL PRO] Failed to fetch script: ${xhr.statusText}`);
script = `importScripts('${fullUrl}');`; // Will fail on Firefox Nightly.
}
// ---------------------------------------
// 🦊 Attention Firefox Addon Reviewer 🦊
// ---------------------------------------
// Please note that this does NOT involve remote code execution. The injected script is bundled
// with the extension. Additionally, there is no custom Content Security Policy (CSP) in use.
const newScript = `
var getParams = () => '${JSON.stringify(params)}';
try {
importScripts('${params.workerScriptURL}');
} catch (error) {
console.error('[TTV LOL PRO] Failed to load script: ${
params.workerScriptURL
}:', error);
}
${script}
`;
const newScriptURL = URL.createObjectURL(
new Blob([newScript], { type: "text/javascript" })
);
// Required for VAFT compatibility.
const wrapperScript = `
try {
importScripts('${newScriptURL}');
} catch (error) {
console.warn('[TTV LOL PRO] Failed to wrap script: ${newScriptURL}:', error);
${newScript}
}
`;
const wrapperScriptURL = URL.createObjectURL(
new Blob([wrapperScript], { type: "text/javascript" })
);
super(wrapperScriptURL, options);
pageState.twitchWorkers.push(this);
this.addEventListener("message", event => {
if (
event.data?.type === MessageType.ContentScriptMessage ||
event.data?.type === MessageType.PageScriptMessage
) {
window.postMessage(event.data);
}
});
// Can't revoke `newScriptURL` because of a conflict with VAFT.
URL.revokeObjectURL(wrapperScriptURL);
}
};
let sendStoreStateToWorker = false;
window.addEventListener("message", event => {
// Relay messages from the content script to the worker script.
if (event.data?.type === MessageType.WorkerScriptMessage) {
sendMessageToWorkerScripts(pageState.twitchWorkers, event.data.message);
return;
}
if (event.data?.type !== MessageType.PageScriptMessage) return;
const message = event.data?.message;
if (!message) return;
switch (message.type) {
case MessageType.GetStoreState: // From Worker
if (pageState.state != null) {
sendMessageToWorkerScripts(pageState.twitchWorkers, {
type: MessageType.GetStoreStateResponse,
state: pageState.state,
});
}
sendStoreStateToWorker = true;
break;
case MessageType.GetStoreStateResponse: // From Content
if (pageState.state == null) {
console.log("[TTV LOL PRO] Received store state from content script.");
} else {
console.debug(
"[TTV LOL PRO] Received store state from content script."
);
}
const state = message.state;
pageState.state = state;
if (sendStoreStateToWorker) {
sendMessageToWorkerScripts(pageState.twitchWorkers, {
type: MessageType.GetStoreStateResponse,
state,
});
}
break;
}
});
function onChannelChange(
callback: (channelName: string, oldChannelName: string | null) => void
) {
let channelName: string | null = findChannelFromTwitchTvUrl(location.href);
const NATIVE_PUSH_STATE = window.history.pushState;
function pushState(
data: any,
unused: string,
url?: string | URL | null | undefined
) {
if (!url) return NATIVE_PUSH_STATE.call(window.history, data, unused);
const fullUrl = toAbsoluteUrl(url.toString());
const newChannelName = findChannelFromTwitchTvUrl(fullUrl);
if (newChannelName != null && newChannelName !== channelName) {
const oldChannelName = channelName;
channelName = newChannelName;
callback(channelName, oldChannelName);
}
return NATIVE_PUSH_STATE.call(window.history, data, unused, url);
}
window.history.pushState = pushState;
const NATIVE_REPLACE_STATE = window.history.replaceState;
function replaceState(
data: any,
unused: string,
url?: string | URL | null | undefined
) {
if (!url) return NATIVE_REPLACE_STATE.call(window.history, data, unused);
const fullUrl = toAbsoluteUrl(url.toString());
const newChannelName = findChannelFromTwitchTvUrl(fullUrl);
if (newChannelName != null && newChannelName !== channelName) {
const oldChannelName = channelName;
channelName = newChannelName;
callback(channelName, oldChannelName);
}
return NATIVE_REPLACE_STATE.call(window.history, data, unused, url);
}
window.history.replaceState = replaceState;
window.addEventListener("popstate", () => {
const newChannelName = findChannelFromTwitchTvUrl(location.href);
if (newChannelName != null && newChannelName !== channelName) {
const oldChannelName = channelName;
channelName = newChannelName;
callback(channelName, oldChannelName);
}
});
}
onChannelChange((_channelName, oldChannelName) => {
sendMessageToContentScript({
type: MessageType.ClearStats,
channelName: oldChannelName,
});
sendMessageToPageScript({
type: MessageType.ClearStats,
channelName: oldChannelName,
});
sendMessageToWorkerScripts(pageState.twitchWorkers, {
type: MessageType.ClearStats,
channelName: oldChannelName,
});
});
sendMessageToContentScript({ type: MessageType.GetStoreState });
document.currentScript!.remove();