-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
main.js
297 lines (240 loc) · 8.24 KB
/
main.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
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
const path = require('path')
const { promises: fs } = require('fs')
const { app, session, BrowserWindow, Menu, MenuItem, clipboard } = require('electron')
const { Tabs } = require('./tabs')
const { Extensions } = require('electron-chrome-extensions')
const { setupMenu } = require('./menu')
const { setupContextMenu } = require('./context-menu')
let webuiExtensionId
const manifestExists = async (dirPath) => {
if (!dirPath) return false
const manifestPath = path.join(dirPath, 'manifest.json')
try {
return (await fs.stat(manifestPath)).isFile()
} catch {
return false
}
}
async function loadExtensions(session, extensionsPath) {
const subDirectories = await fs.readdir(extensionsPath, {
withFileTypes: true,
})
const extensionDirectories = await Promise.all(
subDirectories
.filter((dirEnt) => dirEnt.isDirectory())
.map(async (dirEnt) => {
const extPath = path.join(extensionsPath, dirEnt.name)
if (await manifestExists(extPath)) {
return extPath
}
const extSubDirs = await fs.readdir(extPath, {
withFileTypes: true,
})
const versionDirPath =
extSubDirs.length === 1 && extSubDirs[0].isDirectory()
? path.join(extPath, extSubDirs[0].name)
: null
if (await manifestExists(versionDirPath)) {
return versionDirPath
}
})
)
const results = []
for (const extPath of extensionDirectories.filter(Boolean)) {
console.log(`Loading extension from ${extPath}`)
const extensionInfo = await session.loadExtension(extPath)
results.push(extensionInfo)
}
return results
}
const getParentWindowOfTab = (tab) => {
switch (tab.getType()) {
case 'window':
return BrowserWindow.fromWebContents(tab)
case 'browserView':
case 'webview':
return tab.getOwnerBrowserWindow()
case 'backgroundPage':
return BrowserWindow.getFocusedWindow()
default:
throw new Error(`Unable to find parent window of '${tab.getType()}'`)
}
}
class TabbedBrowserWindow {
constructor(options) {
this.session = options.session || session.defaultSession
const extensions = (this.extensions = options.extensions)
// Can't inheret BrowserWindow
// https://github.com/electron/electron/issues/23#issuecomment-19613241
this.window = new BrowserWindow(options.window)
this.id = this.window.id
this.webContents = this.window.webContents
this.extensions.addExtensionHost(this.webContents)
const webuiUrl = path.join('chrome-extension://', webuiExtensionId, '/webui.html')
this.webContents.loadURL(webuiUrl)
this.tabs = new Tabs(this.window)
this.tabs.on('tab-created', function onTabCreated(tab) {
extensions.addTab(tab.webContents)
if (options.initialUrl) tab.webContents.loadURL(options.initialUrl)
})
this.tabs.on('tab-selected', function onTabSelected(tab) {
extensions.selectTab(tab.webContents)
})
setImmediate(() => {
const initialTab = this.tabs.create()
initialTab.loadURL(options.initialUrl || 'about:blank')
})
}
getFocusedTab() {
return this.tabs.selected
}
}
class Browser {
windows = []
popupView = null
constructor() {
app.whenReady().then(this.init.bind(this))
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
this.destroy()
}
})
app.on('web-contents-created', this.onWebContentsCreated.bind(this))
}
destroy() {
app.quit()
}
getFocusedWindow() {
return this.windows.find((w) => w.window.isFocused()) || this.windows[0]
}
getWindowFromWebContents(webContents) {
const window = getParentWindowOfTab(webContents)
return window ? this.windows.find((win) => win.id === window.id) : null
}
getIpcWindow(event) {
return event.sender ? this.getWindowFromWebContents(event.sender) : null
}
async init() {
this.initSession()
setupMenu(this)
this.extensions = new Extensions({
session: this.session,
createTab: (event, details) => {
const win =
typeof details.windowId === 'number'
? this.windows.find((w) => w.id === details.windowId)
: this.getIpcWindow(event)
const tab = win.tabs.create()
if (details.url) tab.loadURL(details.url || newTabUrl)
if (typeof details.active === 'boolean' ? details.active : true) win.tabs.select(tab.id)
return tab
},
selectTab: (event, tab) => {
const win = this.getIpcWindow(event)
win.tabs.select(tab.id)
},
removeTab: (event, tab) => {
const win = this.getIpcWindow(event)
win.tabs.remove(tab.id)
},
createWindow: (event, details) => {
const win = this.createWindow({
initialUrl: details.url || newTabUrl,
})
// if (details.active) tabs.select(tab.id)
return win.window
},
})
const extensionPreload = path.join(
__dirname,
'../../electron-chrome-extensions/dist/preload.js'
)
const preloads = this.session.getPreloads()
this.session.setPreloads([extensionPreload, ...preloads])
const webuiExtension = await this.session.loadExtension(path.join(__dirname, 'ui'))
webuiExtensionId = webuiExtension.id
const newTabUrl = path.join('chrome-extension://', webuiExtensionId, 'new-tab.html')
const installedExtensions = await loadExtensions(this.session, path.join(__dirname, '../../../extensions'))
this.extensions.browserAction.processExtensions(this.session, installedExtensions)
this.extensions.on('active-tab-changed', (tab) => {
const win = this.getWindowFromWebContents(tab)
win.tabs.select(tab.id)
})
this.extensions.on('action-clicked', (event, extensionId) => {
const win = this.getWindowFromWebContents(event.sender)
const selectedId = win.tabs.selected ? win.tabs.selected.id : -1
if (this.popupView) {
win.window.removeBrowserView(this.popupView)
if (this.popupView.webContents.isDevToolsOpened()) {
this.popupView.webContents.closeDevTools()
}
this.popupView = undefined
} else {
this.popupView = this.extensions.createPopup(win.window, selectedId, extensionId)
}
})
this.createWindow({ initialUrl: newTabUrl })
}
initSession() {
this.session = session.defaultSession
// Remove Electron and App details to closer emulate Chrome's UA
const userAgent = this.session
.getUserAgent()
.replace(/\sElectron\/\S+/, '')
.replace(new RegExp(`\\s${app.getName()}/\\S+`), '')
this.session.setUserAgent(userAgent)
}
createWindow(options) {
const win = new TabbedBrowserWindow({
...options,
extensions: this.extensions,
window: {
width: 1280,
height: 720,
frame: false,
webPreferences: {
sandbox: true,
nodeIntegration: false,
enableRemoteModule: false,
contextIsolation: true,
worldSafeExecuteJavaScript: true,
},
},
})
this.windows.push(win)
if (process.env.DEBUG) {
win.webContents.openDevTools({ mode: 'detach' })
}
return win
}
async onWebContentsCreated(event, webContents) {
const type = webContents.getType()
const url = webContents.getURL()
console.log(`webContents type=${type}, url=${url}`)
if (
webContents.getType() === 'backgroundPage' ||
// TODO: Need changes from this PR for properly assigned background page type
// https://github.com/electron/electron/pull/22217
(webContents.getType() === 'remote' && webContents.getURL().startsWith('chrome-extension://'))
) {
this.extensions.addExtensionHost(webContents)
webContents.openDevTools({ mode: 'detach', activate: true })
}
webContents.on('new-window', (event, url, frameName, disposition, options) => {
event.preventDefault()
switch (disposition) {
case 'foreground-tab':
case 'background-tab':
case 'new-window':
const win = this.getIpcWindow(event)
const tab = win.tabs.create()
tab.loadURL(url)
break
}
})
webContents.on('context-menu', (event, params) => {
setupContextMenu(this, webContents, params)
})
}
}
module.exports = Browser