-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcross_context.js
More file actions
418 lines (383 loc) · 17.6 KB
/
cross_context.js
File metadata and controls
418 lines (383 loc) · 17.6 KB
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
function waitFor(conditionFn, interval = 1000) {
return new Promise(resolve => {
const checkCondition = setInterval(() => {
if (conditionFn()) {
clearInterval(checkCondition);
resolve();
}
}, interval);
});
};
function wait(millis) {
return new Promise(resolve => setTimeout(resolve, millis));
};
function getSensitiveLogPreview(value, maxLength = 10) {
if (value == null) {
return value;
}
let textValue = value;
if (typeof textValue != "string") {
try {
textValue = JSON.stringify(textValue);
} catch (error) {
textValue = String(textValue);
}
}
if (textValue.length <= maxLength) {
return textValue;
}
return `${textValue.substring(0, maxLength)}...`;
}
class CrossContext {
static TYPE_LISTENER = "listener"
static TYPE_CALLER = "caller"
static LISTENER_ADD = "add"
static LISTENER_CALLBACK = "callback"
static TARGET_OFFSCREEN = "target_offscreen"
static TARGET_FOREGROUND = "target_foreground"
static TARGET_SERVICE_WORKER = "target_service_worker"
static RESULT_ERROR = "thesuperdupererrormotherhahaa"
static RESULT_OK = "__crossContextResultOK"
static LISTENER_ID_DEFAULT = "MyListener"
static #listeners = {}
static addForegroundListener({ call, listener, target, addEventListenerType, replyTo }) {
if (!CrossContext.#listeners[call]) {
CrossContext.#listeners[call] = [];
}
CrossContext.#listeners[call].push({ listener, addEventListenerType });
const options = {
call,
type: CrossContext.TYPE_LISTENER,
target,
addEventListenerType,
replyTo
};
chrome.runtime.sendMessage(options)
}
static removeForegroundListener({ call, listener, target, addEventListenerType, replyTo }) {
if (!CrossContext.#listeners[call]) return;
//remove all matching by finding non-matching and assigning those
const nonMatchingListeners = CrossContext.#listeners[call].filter(listener => listener.addEventListenerType != addEventListenerType);
CrossContext.#listeners[call] = nonMatchingListeners;
}
static callForegroundListener(call, addEventListenerTypeForCall, input = []) {
const listenersForCall = CrossContext.#listeners[call];
if (listenersForCall == null) return;
listenersForCall.forEach(listenerOptions => {
const { listener, addEventListenerType } = listenerOptions;
if (addEventListenerType != addEventListenerTypeForCall) return;
// console.log("Calling foreground listener", self, call, listener);
listener(...input)
});
}
static #getBackgroundFunctionFromCall(call) {
if (call.indexOf(".") < 0) {
return self[call];
}
const callParts = call.split('.');
const context = callParts.slice(0, callParts.length - 1).reduce((obj, part) => obj[part], self);
const functionName = callParts[callParts.length - 1];
const fun = context[functionName].bind(context);
return fun;
}
static #backgroundListeners = {}
static addBackgroundListener({ call, id = CrossContext.LISTENER_ID_DEFAULT, addEventListenerType, replyTo }) {
const listenerFunction = CrossContext.#getBackgroundFunctionFromCall(call);
if (listenerFunction == null) return;
const removeListenerFunction = CrossContext.#getBackgroundFunctionFromCall(call
.replace("addListener", "removeListener")
.replace("addEventListener", "removeEventListener")
);
// console.log("Adding background listener", self, call, listenerFunction);
const finalId = call + id;
if (removeListenerFunction) {
const existingListenerWithSameId = CrossContext.#backgroundListeners[finalId];
if (existingListenerWithSameId) {
// console.log("Removing existing listener with same ID", finalId, existingListenerWithSameId)
if (addEventListenerType) {
removeListenerFunction(addEventListenerType, existingListenerWithSameId);
} else {
removeListenerFunction(existingListenerWithSameId);
}
delete CrossContext.#backgroundListeners[finalId];
}
}
const listener = (...input) => {
chrome.runtime.sendMessage({ call, type: CrossContext.TYPE_LISTENER, input, target: replyTo, listenerAddOrCallback: CrossContext.LISTENER_CALLBACK, addEventListenerType });
};
CrossContext.#backgroundListeners[finalId] = listener
if (addEventListenerType) {
listenerFunction(addEventListenerType, listener)
} else {
listenerFunction(listener)
}
}
static listen(call, target = CrossContext.TARGET_SERVICE_WORKER, replyTo = isForegroundPage ? CrossContext.TARGET_FOREGROUND : CrossContext.TARGET_OFFSCREEN) {
return ((...listener) => {
let addEventListenerType = null;
let actualListener = null;
let addEventListenerOptions = null;
if (listener.length > 1) {
[addEventListenerType, actualListener, addEventListenerOptions] = listener;
} else {
actualListener = listener[0];
}
// console.log(`Listening to ${call}`, { self, target, replyTo });
return CrossContext.addForegroundListener({ call, listener: actualListener, target, addEventListenerType, addEventListenerOptions, replyTo })
});
}
static stopListening(call) {
return ((...listener) => {
let addEventListenerType = null;
let actualListener = null;
let addEventListenerOptions = null;
if (listener.length > 1) {
[addEventListenerType, actualListener] = listener;
} else {
actualListener = listener[0];
}
// console.log(`Listening to ${call}`, { self, target, replyTo });
return CrossContext.removeForegroundListener({ call, listener: actualListener, addEventListenerType })
});
}
static async callBackgroundFunction({ call, input, sendResponse, target }) {
const fun = CrossContext.#getBackgroundFunctionFromCall(call);
if (fun == null) {
await sendResponse({ [CrossContext.RESULT_OK]: false });
return;
}
// console.log("Calling background function", self, call, target, fun)
try {
const output = await fun(...input);
await sendResponse({ [CrossContext.RESULT_OK]: true, value: output });
} catch (e) {
const errorResponse = {};
errorResponse[CrossContext.RESULT_ERROR] = { message: e.toString(), stack: e.stack, info: JSON.stringify(e) };
await sendResponse(errorResponse);
}
}
static call(call, target = CrossContext.TARGET_SERVICE_WORKER) {
return (async (...input) => {
const intputWithoutFunctions = input.filter(i => typeof i !== "function");
const maxAttempts = 30;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const result = await chrome.runtime.sendMessage({ call, type: CrossContext.TYPE_CALLER, input: intputWithoutFunctions, target });
const possibleError = result && result[CrossContext.RESULT_ERROR];
if (possibleError) {
console.log("Error from cross context call", possibleError);
throw possibleError;
}
if (result != null && typeof result === "object" && CrossContext.RESULT_OK in result) {
if (result[CrossContext.RESULT_OK]) {
const value = result.value;
const lastArg = input[input.length - 1];
if (typeof lastArg === 'function') {
lastArg(value);
}
return value;
}
// RESULT_OK is false: handler reached but function not available yet
}
// No response (undefined) or not ready — target context not loaded yet, retry
if (attempt < maxAttempts - 1) {
await wait(100);
}
}
console.warn(`CrossContext call "${call}" to ${target} failed: target not ready after ${maxAttempts} attempts`);
return undefined;
});
}
}
const isServiceWorker = typeof ServiceWorkerGlobalScope !== 'undefined' && self instanceof ServiceWorkerGlobalScope;
const isOffscreenPage = self["isOffscreenPage"] ?? false;
const isForegroundPage = self["isForegroundPage"] ?? false;
console.log("Self", self, "Is Service Worker", isServiceWorker, "Is Offscreen Page", isOffscreenPage, "Is Foreground Page", isForegroundPage);
chrome.runtime.onMessage.addListener(({ call, type, input, target, replyTo, addEventListenerType, listenerAddOrCallback = CrossContext.LISTENER_ADD }, sender, sendResponse) => {
if (!call || !target || !type) return false;
const rightTarget = false//!target
|| (target == CrossContext.TARGET_SERVICE_WORKER && isServiceWorker)
|| (target == CrossContext.TARGET_OFFSCREEN && isOffscreenPage)
|| (target == CrossContext.TARGET_FOREGROUND && isForegroundPage);
if (!rightTarget) return;
if (type == CrossContext.TYPE_LISTENER) {
if (listenerAddOrCallback == CrossContext.LISTENER_ADD) {
CrossContext.addBackgroundListener({ call, addEventListenerType, sender, replyTo });
} else {
CrossContext.callForegroundListener(call, addEventListenerType, input);
}
return false;
}
if (type == CrossContext.TYPE_CALLER) {
(async () => {
await CrossContext.callBackgroundFunction({ call, input, target, sendResponse });
})();
return true;
}
});
if (!isServiceWorker) {
const originalChromeRuntime = chrome.runtime;
chrome.commands = {
onCommand: {
addListener: CrossContext.listen("chrome.commands.onCommand.addListener")
},
getAll: CrossContext.call("chrome.commands.getAll")
};
chrome.notifications = {
onClicked: {
addListener: CrossContext.listen("chrome.notifications.onClicked.addListener")
},
onClosed: {
addListener: CrossContext.listen("chrome.notifications.onClosed.addListener")
},
onButtonClicked: {
addListener: CrossContext.listen("chrome.notifications.onButtonClicked.addListener")
},
clear: CrossContext.call("chrome.notifications.clear"),
create: CrossContext.call("chrome.notifications.create")
};
chrome.contextMenus = {
removeAll: CrossContext.call("chrome.contextMenus.removeAll"),
create: CrossContext.call("chrome.contextMenus.create"),
onClicked: {
addListener: CrossContext.listen("chrome.contextMenus.onClicked.addListener")
}
};
chrome.storage = {
sync: {
get: CrossContext.call("chrome.storage.sync.get"),
set: CrossContext.call("chrome.storage.sync.set"),
onChanged: {
addListener: CrossContext.listen("chrome.storage.sync.onChanged.addListener")
}
},
onChanged: {
addListener: CrossContext.listen("chrome.storage.onChanged.addListener")
}
};
chrome.gcm = {
onMessage: {
addListener: CrossContext.listen("chrome.gcm.onMessage.addListener")
}
};
chrome.instanceID = {
getToken: CrossContext.call("chrome.instanceID.getToken")
};
chrome.tabs = {
create: CrossContext.call("chrome.tabs.create"),
query: CrossContext.call("chrome.tabs.query"),
update: CrossContext.call("chrome.tabs.update"),
remove: CrossContext.call("chrome.tabs.remove"),
highlight: CrossContext.call("chrome.tabs.highlight"),
onUpdated: {
addListener: CrossContext.listen("chrome.tabs.onUpdated.addListener"),
removeListener: CrossContext.call("chrome.tabs.onUpdated.removeListener")
},
onRemoved: {
addListener: CrossContext.listen("chrome.tabs.onRemoved.addListener"),
removeListener: CrossContext.call("chrome.tabs.onRemoved.removeListener")
}
};
chrome.windows = {
onRemoved: {
addListener: CrossContext.listen("chrome.windows.onRemoved.addListener")
},
update: CrossContext.call("chrome.windows.update"),
create: CrossContext.call("chrome.windows.create"),
getCurrent: CrossContext.call("chrome.windows.getCurrent")
};
chrome.action = {
setIcon: CrossContext.call("chrome.action.setIcon"),
setBadgeText: CrossContext.call("chrome.action.setBadgeText"),
setBadgeBackgroundColor: CrossContext.call("chrome.action.setBadgeBackgroundColor")
};
chrome.identity = {
getProfileUserInfo: CrossContext.call("chrome.identity.getProfileUserInfo"),
getAuthToken: CrossContext.call("chrome.identity.getAuthToken")
};
chrome.runtime = {
getManifest: CrossContext.call("chrome.runtime.getManifest"),
sendMessage: originalChromeRuntime.sendMessage,
onMessage: originalChromeRuntime.onMessage
}
}
if (isServiceWorker) {
//needed because otherwise if you do too many requests in a row you'll get an exception
const originalGetToken = chrome.instanceID.getToken;
var gcmTokenGetter = null;
const getFromPending = async () => {
const token = await gcmTokenGetter;
console.log("token", getSensitiveLogPreview(token));
gcmTokenGetter = null;
return token;
}
chrome.instanceID.getToken = async function (...input) {
if (gcmTokenGetter) {
console.log("getGCMToken using pending request")
return await getFromPending();
}
console.log("getGCMToken using new request")
gcmTokenGetter = originalGetToken(...input);
return await getFromPending();
}
// I need to replace the original addListener with my own because sometimes gcms will arrive before a background page registers its listeners and those pushes wouldn't be delivered. Wait for the listeners to be available and the push it.
const replaceListenerThatWakesUpServiceWorker = (addListenerOnThis, tag) => {
const joinListeners = [];
addListenerOnThis.addListener(async payload => {
console.log(`Received ${tag} in service worker`, payload)
//if no joinListeners are present, wait until there are some and then send the message
if (joinListeners.length === 0) {
console.log(`No listeners for ${tag}, waiting for listeners to be added`)
await waitFor(() => joinListeners.length > 0, 100);
}
joinListeners.forEach(listener => listener(payload));
});
addListenerOnThis.addListener = async (listener) => {
console.log(`service worker ${tag} onMessage addListener`);
joinListeners.push(listener);
}
addListenerOnThis.removeListener = async (listener) => {
console.log(`service worker ${tag} onMessage removeListener`);
const index = joinListeners.indexOf(listener);
if (index == -1) return;
joinListeners.splice(index, 1);
}
}
replaceListenerThatWakesUpServiceWorker(chrome.contextMenus.onClicked, "context menu click");
replaceListenerThatWakesUpServiceWorker(chrome.gcm.onMessage, "gcm");
// const joinGcmListeners = [];
// const joinContextMenuListeners = [];
// chrome.gcm.onMessage.addListener(async payload => {
// console.log("Received gcm in service worker", payload)
// //if no joinGcmListeners are present, wait until there are some and then send the message
// if (joinGcmListeners.length === 0) {
// console.log("No listeners, waiting for listeners to be added")
// await waitFor(() => joinGcmListeners.length > 0, 100);
// }
// joinGcmListeners.forEach(listener => listener(payload));
// });
// chrome.contextMenus.onClicked.addListener(async payload => {
// console.log("Received context menu click in service worker", payload)
// //if no joinContextMenuListeners are present, wait until there are some and then send the message
// if (joinContextMenuListeners.length === 0) {
// console.log("No listeners for context menu, waiting for listeners to be added")
// await waitFor(() => joinContextMenuListeners.length > 0, 100);
// }
// joinContextMenuListeners.forEach(listener => listener(payload));
// });
// chrome.gcm.onMessage.addListener = async (listener) => {
// console.log("service worker gcm onMessage addListener");
// joinGcmListeners.push(listener);
// }
// chrome.gcm.onMessage.removeListener = async (listener) => {
// console.log("service worker gcm onMessage removeListener");
// joinGcmListeners.push(listener);
// }
// chrome.contextMenus.onClicked.addListener = async (listener) => {
// console.log("service worker contextMenus onClicked addListener");
// joinContextMenuListeners.push(listener);
// }
// chrome.contextMenus.onClicked.removeListener = async (listener) => {
// console.log("service worker contextMenus onClicked removeListener");
// joinContextMenuListeners.push(listener);
// }
}