-
-
Notifications
You must be signed in to change notification settings - Fork 680
/
viewManager.js
322 lines (275 loc) · 9.24 KB
/
viewManager.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
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
const BrowserView = electron.BrowserView
var viewMap = {} // id: view
var viewStateMap = {} // id: view state
var temporaryPopupViews = {} // id: view
const defaultViewWebPreferences = {
nodeIntegration: false,
nodeIntegrationInSubFrames: true,
scrollBounce: true,
safeDialogs: true,
safeDialogsMessage: 'Prevent this page from creating additional dialogs',
preload: __dirname + '/dist/preload.js',
contextIsolation: true,
sandbox: true,
enableRemoteModule: false,
allowPopups: false,
// partition: partition || 'persist:webcontent',
enableWebSQL: false,
autoplayPolicy: (settings.get('enableAutoplay') ? 'no-user-gesture-required' : 'user-gesture-required')
}
function createView (existingViewId, id, webPreferencesString, boundsString, events) {
viewStateMap[id] = { loadedInitialURL: false }
let view
if (existingViewId) {
view = temporaryPopupViews[existingViewId]
delete temporaryPopupViews[existingViewId]
// the initial URL has already been loaded, so set the background color
view.setBackgroundColor('#fff')
viewStateMap[id].loadedInitialURL = true
} else {
view = new BrowserView({ webPreferences: Object.assign({}, defaultViewWebPreferences, JSON.parse(webPreferencesString)) })
}
events.forEach(function (event) {
view.webContents.on(event, function (e) {
var args = Array.prototype.slice.call(arguments).slice(1)
mainWindow.webContents.send('view-event', {
viewId: id,
event: event,
args: args
})
})
})
view.webContents.setWindowOpenHandler(function (details) {
if (details.disposition === 'background-tab') {
mainWindow.webContents.send('view-event', {
viewId: id,
event: 'new-tab',
args: [details.url]
})
return {
action: 'deny'
}
}
return {
action: 'allow'
}
})
view.webContents.removeAllListeners('-add-new-contents')
view.webContents.on('-add-new-contents', function (e, webContents, disposition, _userGesture, _left, _top, _width, _height, url, frameName, referrer, rawFeatures, postData) {
var view = new BrowserView({ webPreferences: defaultViewWebPreferences, webContents: webContents })
var popupId = Math.random().toString()
temporaryPopupViews[popupId] = view
mainWindow.webContents.send('view-event', {
viewId: id,
event: 'did-create-popup',
args: [popupId]
})
})
view.webContents.on('ipc-message', function (e, channel, data) {
mainWindow.webContents.send('view-ipc', {
id: id,
name: channel,
data: data,
frameId: e.frameId
})
})
// Open a login prompt when site asks for http authentication
view.webContents.on('login', (event, authenticationResponseDetails, authInfo, callback) => {
if (authInfo.scheme !== 'basic') { // Only for basic auth
return
}
event.preventDefault()
var title = l('loginPromptTitle').replace('%h', authInfo.host).replace('%r', authInfo.realm)
createPrompt({
text: title,
values: [{ placeholder: l('username'), id: 'username', type: 'text' },
{ placeholder: l('password'), id: 'password', type: 'password' }],
ok: l('dialogConfirmButton'),
cancel: l('dialogSkipButton'),
width: 400,
height: 200
}, function (result) {
// resend request with auth credentials
callback(result.username, result.password)
})
})
// show an "open in app" prompt for external protocols
function handleExternalProtocol (e, url, isInPlace, isMainFrame, frameProcessId, frameRoutingId) {
var knownProtocols = ['http', 'https', 'file', 'min', 'about', 'data', 'javascript', 'chrome'] // TODO anything else?
if (!knownProtocols.includes(url.split(':')[0])) {
var externalApp = app.getApplicationNameForProtocol(url)
if (externalApp) {
// TODO find a better way to do this
// (the reason to use executeJS instead of the Electron dialog API is so we get the "prevent this page from creating additional dialogs" checkbox)
var sanitizedName = externalApp.replace(/[^a-zA-Z0-9.]/g, '')
if (view.webContents.getURL()) {
view.webContents.executeJavaScript('confirm("' + l('openExternalApp').replace('%s', sanitizedName) + '")').then(function (result) {
if (result === true) {
electron.shell.openExternal(url)
}
})
} else {
// the code above tries to show the dialog in a browserview, but if the view has no URL, this won't work.
// so show the dialog globally as a fallback
var result = electron.dialog.showMessageBoxSync({
type: 'question',
buttons: ['OK', 'Cancel'],
message: l('openExternalApp').replace('%s', sanitizedName).replace(/\\/g, '')
})
if (result === 0) {
electron.shell.openExternal(url)
}
}
}
}
}
view.webContents.on('did-start-navigation', handleExternalProtocol)
/*
It's possible for an HTTP request to redirect to an external app link
(primary use case for this is OAuth from desktop app > browser > back to app)
and did-start-navigation isn't (always?) emitted for redirects, so we need this handler as well
*/
view.webContents.on('will-redirect', handleExternalProtocol)
view.setBounds(JSON.parse(boundsString))
viewMap[id] = view
return view
}
function destroyView (id) {
if (!viewMap[id]) {
return
}
if (viewMap[id] === mainWindow.getBrowserView()) {
mainWindow.setBrowserView(null)
}
viewMap[id].webContents.destroy()
delete viewMap[id]
delete viewStateMap[id]
}
function destroyAllViews () {
for (const id in viewMap) {
destroyView(id)
}
}
function setView (id) {
mainWindow.setBrowserView(viewMap[id])
}
function setBounds (id, bounds) {
if (viewMap[id]) {
viewMap[id].setBounds(bounds)
}
}
function focusView (id) {
// empty views can't be focused because they won't propogate keyboard events correctly, see https://github.com/minbrowser/min/issues/616
// also, make sure the view exists, since it might not if the app is shutting down
if (viewMap[id] && (viewMap[id].webContents.getURL() !== '' || viewMap[id].webContents.isLoading())) {
viewMap[id].webContents.focus()
} else if (mainWindow) {
mainWindow.webContents.focus()
}
}
function hideCurrentView () {
mainWindow.setBrowserView(null)
mainWindow.webContents.focus()
}
function getView (id) {
return viewMap[id]
}
function getViewIDFromWebContents (contents) {
for (var id in viewMap) {
if (viewMap[id].webContents === contents) {
return id
}
}
}
ipc.on('createView', function (e, args) {
createView(args.existingViewId, args.id, args.webPreferencesString, args.boundsString, args.events)
})
ipc.on('destroyView', function (e, id) {
destroyView(id)
})
ipc.on('destroyAllViews', function () {
destroyAllViews()
})
ipc.on('setView', function (e, args) {
setView(args.id)
setBounds(args.id, args.bounds)
if (args.focus) {
focusView(args.id)
}
})
ipc.on('setBounds', function (e, args) {
setBounds(args.id, args.bounds)
})
ipc.on('focusView', function (e, id) {
focusView(id)
})
ipc.on('hideCurrentView', function (e) {
hideCurrentView()
})
ipc.on('loadURLInView', function (e, args) {
// wait until the first URL is loaded to set the background color so that new tabs can use a custom background
if (!viewStateMap[args.id].loadedInitialURL) {
viewMap[args.id].setBackgroundColor('#fff')
}
viewMap[args.id].webContents.loadURL(args.url)
viewStateMap[args.id].loadedInitialURL = true
})
ipc.on('callViewMethod', function (e, data) {
var error, result
try {
var webContents = viewMap[data.id].webContents
var methodOrProp = webContents[data.method]
if (methodOrProp instanceof Function) {
// call function
result = methodOrProp.apply(webContents, data.args)
} else {
// set property
if (data.args && data.args.length > 0) {
webContents[data.method] = data.args[0]
}
// read property
result = methodOrProp
}
} catch (e) {
error = e
}
if (result instanceof Promise) {
result.then(function (result) {
if (data.callId) {
mainWindow.webContents.send('async-call-result', { callId: data.callId, error: null, result })
}
})
result.catch(function (error) {
if (data.callId) {
mainWindow.webContents.send('async-call-result', { callId: data.callId, error, result: null })
}
})
} else if (data.callId) {
mainWindow.webContents.send('async-call-result', { callId: data.callId, error, result })
}
})
ipc.on('getCapture', function (e, data) {
var view = viewMap[data.id]
if (!view) {
// view could have been destroyed
return
}
view.webContents.capturePage().then(function (img) {
var size = img.getSize()
if (size.width === 0 && size.height === 0) {
return
}
img = img.resize({ width: data.width, height: data.height })
mainWindow.webContents.send('captureData', { id: data.id, url: img.toDataURL() })
})
})
ipc.on('saveViewCapture', function (e, data) {
var view = viewMap[data.id]
if (!view) {
// view could have been destroyed
}
view.webContents.capturePage().then(function (image) {
view.webContents.downloadURL(image.toDataURL())
})
})
global.getView = getView