-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathwebExtension.ts
268 lines (230 loc) · 9.53 KB
/
webExtension.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
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
import {ClientType} from "../../clientType";
import {Constants} from "../../constants";
import {ResponsePackage} from "../../responsePackage";
import {UrlUtils} from "../../urlUtils";
import {TooltipType} from "../../clipperUI/tooltipType";
import {VideoUtils} from "../../domParsers/videoUtils";
import {Localization} from "../../localization/localization";
import * as Log from "../../logging/log";
import {ClipperData} from "../../storage/clipperData";
import {LocalStorage} from "../../storage/localStorage";
import {ChangeLog} from "../../versioning/changeLog";
import {Version} from "../../versioning/version";
import {ExtensionBase} from "../extensionBase";
import {InvokeInfo} from "../invokeInfo";
import {InvokeSource} from "../invokeSource";
import {InvokeMode, InvokeOptions} from "../invokeOptions";
import {InjectUrls} from "./injectUrls";
import {WebExtensionWorker} from "./webExtensionWorker";
// We are using the typing from chrome.d.ts, but it is the same for all of the WebExtensions
type Browser = typeof chrome;
type Tab = chrome.tabs.Tab;
export class WebExtension extends ExtensionBase<WebExtensionWorker, W3CTab, number> {
public static browser: Browser;
public static offscreenUrl: string;
public injectUrls: InjectUrls;
constructor(clientType: ClientType, injectUrls: InjectUrls) {
super(clientType, new ClipperData(new LocalStorage()));
this.injectUrls = injectUrls;
this.registerBrowserButton();
this.clipperIdProcessed.then(() => {
this.registerContextMenuItems();
});
this.registerInstallListener();
this.registerTabCreateOrUpdateListener();
this.registerTabRemoveListener();
}
public static getExtensionVersion(): string {
return WebExtension.browser.runtime.getManifest().version;
}
protected addPageNavListener(callback: (tab: W3CTab) => void) {
WebExtension.browser.webNavigation.onCompleted.addListener((details) => {
// The callback is called on iframes as well, so we ignore those as we are only interested in main frame navigation
if (details.frameId === 0) {
WebExtension.browser.tabs.get(details.tabId, (tab: W3CTab) => {
if (!WebExtension.browser.runtime.lastError && tab) {
callback(tab);
}
});
}
});
}
protected checkIfTabIsOnWhitelistedUrl(tab: W3CTab): boolean {
return !UrlUtils.onBlacklistedDomain(tab.url) && UrlUtils.onWhitelistedDomain(tab.url);
}
protected createWorker(tab: W3CTab): WebExtensionWorker {
return new WebExtensionWorker(this.injectUrls, tab, this.clientInfo, this.auth);
}
protected getIdFromTab(tab: W3CTab): number {
return tab.id;
}
protected onFirstRun() {
// Don't do anything since we're using the onInstalled functionality instead, unless it's not available
// then we use our 'missing-clipperId' heuristic
if (!this.onInstalledSupported()) {
this.clipperIdProcessed.then(() => {
this.onInstalled();
});
}
}
protected checkIfTabMatchesATooltipType(tab: W3CTab, tooltipTypes: TooltipType[]): TooltipType {
if (UrlUtils.onBlacklistedDomain(tab.url)) {
return undefined;
}
return UrlUtils.checkIfUrlMatchesAContentType(tab.url, tooltipTypes);
}
protected async checkIfTabIsAVideoDomain(tab: W3CTab): Promise<boolean> {
let domain = await VideoUtils.videoDomainIfSupported(tab.url);
return !!domain;
}
private invokeClipperInTab(tab: W3CTab, invokeInfo: InvokeInfo, options: InvokeOptions) {
/**
* Create a worker only after the clipperId is processed, since the clientInfo is available
* only after the clipperId is processed. This is to ensure that the worker is created with the
* correct clientInfo.
*/
this.clipperIdProcessed.then(() => {
let worker = this.getOrCreateWorkerForTab(tab, this.getIdFromTab);
worker.closeAllFramesAndInvokeClipper(invokeInfo, options);
});
}
private onInstalled() {
// Send users to our installed page (redirect if they're already on our page, else open a new tab)
WebExtension.browser.tabs.query({ active: true, lastFocusedWindow: true }, (tabs: Tab[]) => {
let isInlineInstall: boolean = ExtensionBase.isOnOneNoteDomain(tabs[0].url);
let installUrl = this.getClipperInstalledPageUrl(this.clientInfo.get().clipperId, this.clientInfo.get().clipperType, isInlineInstall);
if (isInlineInstall) {
WebExtension.browser.tabs.update(tabs[0].id, { url: installUrl });
} else {
WebExtension.browser.tabs.create({ url: installUrl });
}
});
}
private registerBrowserButton() {
WebExtension.browser.action.onClicked.addListener((tab: W3CTab) => {
this.invokeClipperInTab(tab, { invokeSource: InvokeSource.ExtensionButton }, { invokeMode: InvokeMode.Default });
});
}
private registerContextMenuItems() {
// Front-load our localization so our context menu is always localized
this.fetchAndStoreLocStrings().then(() => {
WebExtension.browser.contextMenus.removeAll(() => {
let menus: chrome.contextMenus.CreateProperties[] = [{
id: "WebClipper.Label.OneNoteWebClipper",
title: Localization.getLocalizedString("WebClipper.Label.OneNoteWebClipper"),
contexts: ["page"]
}, {
id: "WebClipper.Label.ClipSelectionToOneNote",
title: Localization.getLocalizedString("WebClipper.Label.ClipSelectionToOneNote"),
contexts: ["selection"]
}, {
id: "WebClipper.Label.ClipImageToOneNote",
title: Localization.getLocalizedString("WebClipper.Label.ClipImageToOneNote"),
contexts: ["image"]
}];
let documentUrlPatternList: string[];
switch (this.clientInfo.get().clipperType) {
case ClientType.ChromeExtension:
documentUrlPatternList = [
"http://*/*",
"https://*/*",
"chrome-extension://encfpfilknmenlmjemepncnlbbjlabkc/*", // PDF.js
"chrome-extension://oemmndcbldboiebfnladdacbdfmadadm/*", // Ad PDF Viewer
"chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/*" // Chrome PDF Viewer
];
break;
case ClientType.EdgeExtension:
// Note that in Edge, the ms-browser-extension:// URL causes the context menus to break.
documentUrlPatternList = [
"http://*/*",
"https://*/*"
];
break;
case ClientType.FirefoxExtension:
// Note that documentUrlPatterns is not supported in Firefox as of 07/22/16
// https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities
// If you include documentUrlPatterns in Firefox, the context menu won't be added!
break;
default:
break;
}
for (let i = 0; i < menus.length; i++) {
if (documentUrlPatternList) {
menus[i].documentUrlPatterns = documentUrlPatternList;
}
WebExtension.browser.contextMenus.create(menus[i]);
WebExtension.browser.contextMenus.onClicked.addListener((info, tab: W3CTab) => {
switch (info.menuItemId) {
case "WebClipper.Label.OneNoteWebClipper":
this.invokeClipperInTab(tab, { invokeSource: InvokeSource.ContextMenu }, { invokeMode: InvokeMode.Default });
break;
case "WebClipper.Label.ClipSelectionToOneNote":
let invokeOptions: InvokeOptions = { invokeMode: InvokeMode.ContextTextSelection };
// If the tab index is negative, chances are the user is using some sort of PDF plugin,
// and the tab object will be invalid. We need to get the parent tab in this scenario.
if (tab.index < 0) {
// Since we are in a PDF plugin, Rangy won't work, so we rely on WebExtension API to grab pure text
invokeOptions.invokeDataForMode = info.selectionText;
WebExtension.browser.tabs.query({ active: true, currentWindow: true }, (tabs: W3CTab[]) => {
// There will only be one tab that meets this criteria
let parentTab = tabs[0];
this.invokeClipperInTab(parentTab, { invokeSource: InvokeSource.ContextMenu }, invokeOptions);
});
} else {
this.invokeClipperInTab(tab, { invokeSource: InvokeSource.ContextMenu }, invokeOptions);
}
break;
case "WebClipper.Label.ClipImageToOneNote":
// Even though we know the user right-clicked an image, srcUrl is only present if the src attr exists
this.invokeClipperInTab(tab, { invokeSource: InvokeSource.ContextMenu }, info.srcUrl ? {
// srcUrl will always be the full url, not relative
invokeDataForMode: info.srcUrl, invokeMode: InvokeMode.ContextImage
} : undefined);
break;
default:
}
});
}
});
});
}
private registerInstallListener() {
// onInstalled is undefined as of Firefox 48
if (this.onInstalledSupported()) {
WebExtension.browser.runtime.onInstalled.addListener(details => {
if (details.reason === "install") {
this.clipperIdProcessed.then(() => {
this.onInstalled();
});
}
});
}
}
private registerTabRemoveListener() {
WebExtension.browser.tabs.onRemoved.addListener((tabId: number) => {
let worker = this.getExistingWorkerForTab(tabId);
if (worker) {
this.removeWorker(worker);
}
});
}
private registerTabCreateOrUpdateListener() {
const matchesAnyUnclippablePage = (url) => {
const unclippablePages = ["chrome://*", "edge://*"];
return unclippablePages.some(unclippablePage => url.match(unclippablePage));
};
WebExtension.browser.tabs.onCreated.addListener((tab: W3CTab) => {
if (matchesAnyUnclippablePage(tab.url)) {
WebExtension.browser.action.disable(tab.id);
}
});
WebExtension.browser.tabs.onUpdated.addListener((tabId: number, changeInfo: any, tab: W3CTab) => {
if (matchesAnyUnclippablePage(tab.url)) {
WebExtension.browser.action.disable(tabId);
}
});
}
private onInstalledSupported(): boolean {
return !!WebExtension.browser.runtime.onInstalled;
}
}