This repository has been archived by the owner on Dec 27, 2022. It is now read-only.
/
browser.js
777 lines (670 loc) · 21.7 KB
/
browser.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
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
import {app, dialog, BrowserWindow, BrowserView, webContents, ipcMain, shell, Menu, screen, session, nativeImage} from 'electron'
import {autoUpdater} from 'electron-updater'
import os from 'os'
import path from 'path'
import fs from 'fs'
import jetpack from 'fs-jetpack'
import ICO from 'icojs'
import toIco from 'to-ico'
import emitStream from 'emit-stream'
import EventEmitter from 'events'
import LRU from 'lru'
const exec = require('util').promisify(require('child_process').exec)
import * as logLib from './logger'
const logger = logLib.child({category: 'browser'})
import * as settingsDb from './dbs/settings'
import * as users from './filesystem/users'
import dat from './dat/index'
import {open as openUrl} from './open-url'
import {getUserSessionFor, setUserSessionFor} from './ui/windows'
import * as tabManager from './ui/tab-manager'
import { updateSetupState } from './ui/setup-flow'
import * as modals from './ui/subwindows/modals'
import * as siteInfo from './ui/subwindows/site-info'
import { findWebContentsParentWindow } from './lib/electron'
import { getEnvVar } from './lib/env'
// constants
// =
const IS_FROM_SOURCE = (process.defaultApp || /node_modules[\\/]electron[\\/]/.test(process.execPath))
const IS_LINUX = !(/^win/.test(process.platform)) && process.platform !== 'darwin'
const DOT_DESKTOP_FILENAME = 'appimagekit-beaker-browser.desktop'
const isBrowserUpdatesSupported = !(IS_LINUX || IS_FROM_SOURCE) // linux is temporarily not supported
// how long between scheduled auto updates?
const SCHEDULED_AUTO_UPDATE_DELAY = 24 * 60 * 60 * 1e3 // once a day
// possible updater states
const UPDATER_STATUS_IDLE = 'idle'
const UPDATER_STATUS_CHECKING = 'checking'
const UPDATER_STATUS_DOWNLOADING = 'downloading'
const UPDATER_STATUS_DOWNLOADED = 'downloaded'
// globals
// =
// dont automatically check for updates (need to respect user preference)
autoUpdater.autoDownload = false
// what's the updater doing?
var updaterState = UPDATER_STATUS_IDLE
var updaterError = false // has there been an error?
// content-type tracker
var resourceContentTypes = new LRU(100) // URL -> Content-Type
// events emitted to rpc clients
var browserEvents = new EventEmitter()
process.on('unhandledRejection', (reason, p) => {
console.error('Unhandled Rejection at: Promise', p, 'reason:', reason)
logger.error(`Unhandled Rejection at: Promise ${p.toString()} reason: ${reason.toString()}`)
})
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err)
logger.error(`Uncaught exception: ${err.toString()}`)
})
// exported methods
// =
export async function setup () {
// setup auto-updater
if (isBrowserUpdatesSupported) {
try {
autoUpdater.setFeedURL(getAutoUpdaterFeedSettings())
autoUpdater.on('update-available', onUpdateAvailable)
autoUpdater.on('update-not-available', onUpdateNotAvailable)
autoUpdater.on('update-downloaded', onUpdateDownloaded)
autoUpdater.on('error', onUpdateError)
} catch (e) {
logger.error(`Auto-updater error: ${e.toString()}`)
}
setTimeout(scheduledAutoUpdate, 15e3) // wait 15s for first run
}
// create a new user if none exists
var defaultUser = await users.getDefault()
if (!defaultUser) {
let archive = await dat.archives.createNewArchive({
title: 'Anonymous',
type: 'unwalled.garden/person'
})
await archive.pda.writeFile('/thumb.jpg', await jetpack.cwd(__dirname).cwd('assets/img').readAsync('default-user-thumb.jpg', 'buffer'), 'binary')
await users.add(archive.url, true)
}
// wire up events
app.on('web-contents-created', onWebContentsCreated)
// window.prompt handling
// - we have use ipc directly instead of using rpc, because we need custom
// response-lifecycle management in the main thread
ipcMain.on('page-prompt-dialog', async (e, message, def) => {
var res = await modals.create(e.sender, 'prompt', {message, default: def}).catch(e => false)
e.returnValue = res && res.value ? res.value : false
})
// HACK
// Electron has an issue where browserviews fail to calculate click regions after a resize
// https://github.com/electron/electron/issues/14038
// we can solve this by forcing a recalculation after every resize
// -prf
ipcMain.on('resize-hackfix', (e, message) => {
var win = findWebContentsParentWindow(e.sender)
if (win) {
win.webContents.executeJavaScript(`if (window.forceUpdateDragRegions) { window.forceUpdateDragRegions() }`)
}
})
// HACK
// Electron doesn't give us a convenient way to check the content-types of responses
// so we track the last 100 responses' headers to accomplish this
// -prf
session.defaultSession.webRequest.onCompleted(onCompleted)
}
export const WEBAPI = {
createEventsStream,
getInfo,
checkForUpdates,
restartBrowser,
getUserSession,
setUserSession,
showEditProfileModal,
getSetting,
getSettings,
setSetting,
updateSetupState,
setStartPageBackgroundImage,
getDefaultProtocolSettings,
setAsDefaultProtocolClient,
removeAsDefaultProtocolClient,
fetchBody,
downloadURL,
readFile,
getResourceContentType,
listBuiltinFavicons,
getBuiltinFavicon,
uploadFavicon,
imageToIco,
executeSidebarCommand,
toggleSiteInfo,
toggleLiveReloading,
setWindowDimensions,
setWindowDragModeEnabled,
setSidebarResizeModeEnabled,
moveWindow,
maximizeWindow,
showOpenDialog,
showContextMenu,
async showModal (name, opts) {
return modals.create(this.sender, name, opts)
},
gotoUrl,
refreshPage,
focusPage,
executeJavaScriptInPage,
injectCssInPage,
uninjectCssInPage,
getTabDriveHandler,
setTabDriveHandler,
openUrl: (url, opts) => { openUrl(url, opts) }, // dont return anything
openFolder,
doWebcontentsCmd,
doTest,
closeModal: () => {} // DEPRECATED, probably safe to remove soon
}
export function fetchBody (url) {
return new Promise((resolve) => {
var http = url.startsWith('https') ? require('https') : require('http')
http.get(url, (res) => {
var body = ''
res.setEncoding('utf8')
res.on('data', (data) => { body += data })
res.on('end', () => resolve(body))
})
})
}
export async function downloadURL (url) {
this.sender.downloadURL(url)
}
function readFile (pathname, opts) {
return new Promise((resolve, reject) => {
fs.readFile(pathname, opts, (err, res) => {
if (err) reject(err)
else resolve(res)
})
})
}
export function getResourceContentType (url) {
let i = url.indexOf('#')
if (i !== -1) url = url.slice(0, i) // strip the fragment
return resourceContentTypes.get(url)
}
export async function listBuiltinFavicons ({filter, offset, limit} = {}) {
if (filter) {
filter = new RegExp(filter, 'i')
}
// list files in assets/favicons and filter on the name
var dir = jetpack.cwd(__dirname).cwd('assets/favicons')
var items = (await dir.listAsync())
.filter(filename => {
if (filter && !filter.test(filename)) {
return false
}
return filename.endsWith('.ico')
})
return items.slice(offset || 0, limit || Number.POSITIVE_INFINITY)
}
export async function getBuiltinFavicon (name) {
var dir = jetpack.cwd(__dirname).cwd('assets/favicons')
return dir.readAsync(name, 'buffer')
}
export async function uploadFavicon () {
let favicon = dialog.showOpenDialog({
title: 'Upload Favicon...',
defaultPath: app.getPath('home'),
buttonLabel: 'Upload Favicon',
filters: [
{ name: 'Images', extensions: ['png', 'ico', 'jpg'] }
],
properties: ['openFile']
})
if (!favicon) return
let faviconBuffer = await jetpack.readAsync(favicon[0], 'buffer')
let extension = path.extname(favicon[0])
if (extension === '.png') {
return toIco(faviconBuffer, {resize: true})
}
if (extension === '.jpg') {
let imageToPng = nativeImage.createFromBuffer(faviconBuffer).toPNG()
return toIco(imageToPng, {resize: true})
}
if (extension === '.ico' && ICO.isICO(faviconBuffer)) {
return faviconBuffer
}
}
export async function imageToIco (image) {
// TODO expand on this function to be png/jpg to ico
let imageToPng = nativeImage.createFromDataURL(image).toPNG()
return toIco(imageToPng, {resize: true})
}
async function executeSidebarCommand (...args) {
return getSenderTab(this.sender).executeSidebarCommand(...args)
}
async function toggleSiteInfo (override) {
var win = findWebContentsParentWindow(this.sender)
if (override === true) {
siteInfo.show(win)
} else if (override === false) {
siteInfo.hide(win)
} else {
siteInfo.toggle(win)
}
}
export async function toggleLiveReloading (enabled) {
var win = findWebContentsParentWindow(this.sender)
tabManager.getActive(win).toggleLiveReloading(enabled)
}
export async function setWindowDimensions ({width, height} = {}) {
var win = findWebContentsParentWindow(this.sender)
var [currentWidth, currentHeight] = win.getSize()
width = width || currentWidth
height = height || currentHeight
win.setSize(width, height)
}
var _windowDragInterval = undefined
export async function setWindowDragModeEnabled (enabled) {
var win = findWebContentsParentWindow(this.sender)
if (enabled) {
if (_windowDragInterval) return
// poll the mouse cursor every 15ms
var lastPt = screen.getCursorScreenPoint()
_windowDragInterval = setInterval(() => {
var newPt = screen.getCursorScreenPoint()
// if the mouse has moved, move the window accordingly
var delta = {x: newPt.x - lastPt.x, y: newPt.y - lastPt.y}
if (delta.x || delta.y) {
var pos = win.getPosition()
win.setPosition(pos[0] + delta.x, pos[1] + delta.y)
lastPt = newPt
}
// if the mouse has moved out of the window, stop
var bounds = win.getBounds()
if (newPt.x < bounds.x || newPt.y < bounds.y || newPt.x > (bounds.x + bounds.width) || newPt.y > (bounds.y + bounds.height)) {
clearInterval(_windowDragInterval)
_windowDragInterval = undefined
}
}, 15)
} else {
// stop the poll
if (!_windowDragInterval) return
clearInterval(_windowDragInterval)
_windowDragInterval = undefined
}
}
var _sidebarResizeInterval = undefined
export async function setSidebarResizeModeEnabled (enabled) {
var win = findWebContentsParentWindow(this.sender)
var tab = tabManager.getActive(win)
if (!win || !tab) return
if (enabled) {
if (_sidebarResizeInterval) return
// poll the mouse cursor every 15ms
_sidebarResizeInterval = setInterval(() => {
var bounds = win.getBounds()
var pt = screen.getCursorScreenPoint()
tab.setSidebarWidth(pt.x - bounds.x)
}, 15)
} else {
if (!_sidebarResizeInterval) return
clearInterval(_sidebarResizeInterval)
_sidebarResizeInterval = undefined
}
}
export async function moveWindow (x, y) {
var win = findWebContentsParentWindow(this.sender)
var pos = win.getPosition()
win.setPosition(pos[0] + x, pos[1] + y)
}
export async function maximizeWindow () {
var win = findWebContentsParentWindow(this.sender)
win.maximize()
}
export function setStartPageBackgroundImage (srcPath, appendCurrentDir) {
if (appendCurrentDir) {
srcPath = path.join(__dirname, `/${srcPath}`)
}
var destPath = path.join(app.getPath('userData'), 'start-background-image')
return new Promise((resolve) => {
if (srcPath) {
fs.readFile(srcPath, (_, data) => {
fs.writeFile(destPath, data, () => resolve())
})
} else {
fs.unlink(destPath, () => resolve())
}
})
}
export async function getDefaultProtocolSettings () {
if (IS_LINUX) {
// HACK
// xdb-settings doesnt currently handle apps that you can't `which`
// we can just use xdg-mime directly instead
// see https://github.com/beakerbrowser/beaker/issues/915
// -prf
let [httpHandler, datHandler] = await Promise.all([
// If there is no default specified, be sure to catch any error
// from exec and return '' otherwise Promise.all errors out.
exec('xdg-mime query default "x-scheme-handler/http"').catch(err => ''),
exec('xdg-mime query default "x-scheme-handler/dat"').catch(err => '')
])
if (httpHandler && httpHandler.stdout) httpHandler = httpHandler.stdout
if (datHandler && datHandler.stdout) datHandler = datHandler.stdout
return {
http: (httpHandler || '').toString().trim() === DOT_DESKTOP_FILENAME,
dat: (datHandler || '').toString().trim() === DOT_DESKTOP_FILENAME
}
}
return Promise.resolve(['http', 'dat'].reduce((res, x) => {
res[x] = app.isDefaultProtocolClient(x)
return res
}, {}))
}
export async function setAsDefaultProtocolClient (protocol) {
if (IS_LINUX) {
// HACK
// xdb-settings doesnt currently handle apps that you can't `which`
// we can just use xdg-mime directly instead
// see https://github.com/beakerbrowser/beaker/issues/915
// -prf
await exec(`xdg-mime default ${DOT_DESKTOP_FILENAME} "x-scheme-handler/${protocol}"`)
return true
}
return Promise.resolve(app.setAsDefaultProtocolClient(protocol))
}
export function removeAsDefaultProtocolClient (protocol) {
return Promise.resolve(app.removeAsDefaultProtocolClient(protocol))
}
export function getInfo () {
return {
version: app.getVersion(),
electronVersion: process.versions.electron,
chromiumVersion: process.versions.chrome,
nodeVersion: process.versions.node,
platform: os.platform(),
updater: {
isBrowserUpdatesSupported,
error: updaterError,
state: updaterState
},
paths: {
userData: app.getPath('userData')
}
}
}
export function checkForUpdates (opts = {}) {
// dont overlap
if (updaterState != UPDATER_STATUS_IDLE) { return }
// update global state
logger.info('[AUTO-UPDATE] Checking for a new version.')
updaterError = false
setUpdaterState(UPDATER_STATUS_CHECKING)
if (opts.prerelease) {
logger.info('[AUTO-UPDATE] Jumping to pre-releases.')
autoUpdater.allowPrerelease = true
}
autoUpdater.checkForUpdates()
// just return a resolve; results will be emitted
return Promise.resolve()
}
export function restartBrowser () {
if (updaterState == UPDATER_STATUS_DOWNLOADED) {
// run the update installer
autoUpdater.quitAndInstall()
logger.info('[AUTO-UPDATE] Quitting and installing.')
} else {
logger.info('Restarting Beaker by restartBrowser()')
// do a simple restart
app.relaunch()
setTimeout(() => app.exit(0), 1e3)
}
}
async function getUserSession () {
var sess = getUserSessionFor(this.sender)
// get session user info
if (!sess) return null
return users.get(sess.url)
}
async function setUserSession (url) {
// normalize the url
var urlp = new URL(url)
url = urlp.origin
// lookup the user
var user = await users.get(url)
if (!user) throw new Error('Invalid user URL')
// set the session
var userSession = {url: user.url}
setUserSessionFor(this.sender, userSession)
}
async function showEditProfileModal () {
var user
var sess = await getUserSession.call(this)
if (sess) user = await users.get(sess.url)
else user = await users.getDefault()
await modals.create(this.sender, 'user', user)
return users.get(user.url)
}
export function getSetting (key) {
return settingsDb.get(key)
}
export function getSettings () {
return settingsDb.getAll()
}
export function setSetting (key, value) {
return settingsDb.set(key, value)
}
const SCROLLBAR_WIDTH = 16
export async function capturePage (url, opts) {
var width = opts.width || 1024
var height = opts.height || 768
var win = new BrowserWindow({
width: width + SCROLLBAR_WIDTH,
height,
show: false,
defaultEncoding: 'UTF-8',
partition: 'session-' + Date.now() + Math.random(),
preload: 'file://' + path.join(app.getAppPath(), 'fg', 'webview-preload', 'index.build.js'),
webPreferences: {
webSecurity: true,
allowRunningInsecureContent: false,
nativeWindowOpen: true
}
})
win.loadURL(url)
// wait for load
await new Promise((resolve, reject) => {
win.webContents.on('did-finish-load', resolve)
})
await new Promise(r => setTimeout(r, 200)) // give an extra 200ms for rendering
// capture the page
var image = await new Promise((resolve, reject) => {
win.webContents.capturePage({x: 0, y: 0, width, height}, resolve)
})
// resize if asked
if (opts.resizeTo) {
image = image.resize(opts.resizeTo)
}
return image.toPNG()
}
// rpc methods
// =
function createEventsStream () {
return emitStream(browserEvents)
}
function showOpenDialog (opts = {}) {
var wc = this.sender
return new Promise((resolve) => {
dialog.showOpenDialog({
title: opts.title,
buttonLabel: opts.buttonLabel,
filters: opts.filters,
properties: opts.properties,
defaultPath: opts.defaultPath
}, filenames => {
wc.focus() // return focus back to the the page
resolve(filenames)
})
})
}
function showContextMenu (menuDefinition) {
return new Promise(resolve => {
var cursorPos = screen.getCursorScreenPoint()
// add a click item to all menu items
addClickHandler(menuDefinition)
function addClickHandler (items) {
items.forEach(item => {
if (item.type === 'submenu' && Array.isArray(item.submenu)) {
addClickHandler(item.submenu)
} else if (item.type !== 'separator' && item.id) {
item.click = clickHandler
}
})
}
// add 'inspect element' in development
if (getEnvVar('NODE_ENV') === 'develop' || getEnvVar('NODE_ENV') === 'test') {
menuDefinition.push({type: 'separator'})
menuDefinition.push({
label: 'Inspect Element',
click: () => {
this.sender.inspectElement(cursorPos.x, cursorPos.y)
if (this.sender.isDevToolsOpened()) { this.sender.devToolsWebContents.focus() }
}
})
}
// track the selection
var selection
function clickHandler (item) {
selection = item.id
}
// show the menu
var win = findWebContentsParentWindow(this.sender)
var menu = Menu.buildFromTemplate(menuDefinition)
menu.popup({window: win})
resolve(selection)
})
}
async function gotoUrl (url) {
getSenderTab(this.sender).loadURL(url)
}
async function refreshPage () {
getSenderTab(this.sender).webContents.reload()
}
async function focusPage () {
getSenderTab(this.sender).focus()
}
async function executeJavaScriptInPage (js) {
return getSenderTab(this.sender).webContents.executeJavaScript(js, true)
.catch(err => {
if (err.toString().includes('Script failed to execute')) {
throw "Injected script failed to execute"
}
throw err
})
}
async function injectCssInPage (css) {
return getSenderTab(this.sender).webContents.insertCSS(css)
}
async function uninjectCssInPage (key) {
return getSenderTab(this.sender).webContents.removeInsertedCSS(key)
}
async function getTabDriveHandler () {
return getSenderTab(this.sender).getDriveHandler()
}
async function setTabDriveHandler (handler) {
return getSenderTab(this.sender).setDriveHandler(handler)
}
function openFolder (folderPath) {
shell.openExternal('file://' + folderPath)
}
async function doWebcontentsCmd (method, wcId, ...args) {
var wc = webContents.fromId(+wcId)
if (!wc) throw new Error(`WebContents not found (${wcId})`)
return wc[method](...args)
}
async function doTest (test) {
}
// internal methods
// =
function getSenderTab (sender) {
var view = BrowserView.fromWebContents(sender)
if (view) {
let tab = tabManager.findTab(view)
if (tab) return tab
}
var win = findWebContentsParentWindow(this.sender)
return tabManager.getActive(win)
}
function setUpdaterState (state) {
updaterState = state
browserEvents.emit('updater-state-changed', {state})
}
function getAutoUpdaterFeedSettings () {
return {
provider: 'github',
repo: 'beaker',
owner: 'beakerbrowser',
vPrefixedTagName: false
}
}
// run a daily check for new updates
function scheduledAutoUpdate () {
settingsDb.get('auto_update_enabled').then(v => {
// if auto updates are enabled, run the check
if (+v === 1) { checkForUpdates() }
// schedule next check
setTimeout(scheduledAutoUpdate, SCHEDULED_AUTO_UPDATE_DELAY)
})
}
// event handlers
// =
function onUpdateAvailable () {
logger.info('[AUTO-UPDATE] New version available. Downloading...')
autoUpdater.downloadUpdate()
setUpdaterState(UPDATER_STATUS_DOWNLOADING)
}
function onUpdateNotAvailable () {
logger.info('[AUTO-UPDATE] No browser update available.')
setUpdaterState(UPDATER_STATUS_IDLE)
}
function onUpdateDownloaded () {
logger.info('[AUTO-UPDATE] New browser version downloaded. Ready to install.')
setUpdaterState(UPDATER_STATUS_DOWNLOADED)
}
function onUpdateError (e) {
console.error(e)
logger.error(`[AUTO-UPDATE] error: ${e.toString()}`)
setUpdaterState(UPDATER_STATUS_IDLE)
updaterError = {message: (e.toString() || '').split('\n')[0]}
browserEvents.emit('updater-error', updaterError)
}
function onWebContentsCreated (e, webContents) {
webContents.on('will-prevent-unload', onWillPreventUnload)
webContents.on('remote-require', e => {
// do not allow
e.preventDefault()
})
webContents.on('remote-get-global', e => {
// do not allow
e.preventDefault()
})
}
function onWillPreventUnload (e) {
var choice = dialog.showMessageBox({
type: 'question',
buttons: ['Leave', 'Stay'],
title: 'Do you want to leave this site?',
message: 'Changes you made may not be saved.',
defaultId: 0,
cancelId: 1
})
var leave = (choice === 0)
if (leave) {
e.preventDefault()
}
}
function onCompleted (details) {
function set (v) {
resourceContentTypes.set(details.url, Array.isArray(v) ? v[0] : v)
}
if (!details.responseHeaders) return
if ('Content-Type' in details.responseHeaders) {
set(details.responseHeaders['Content-Type'])
} else if ('content-type' in details.responseHeaders) {
set(details.responseHeaders['content-type'])
}
}