/
api-web-contents-spec.ts
358 lines (320 loc) · 12.5 KB
/
api-web-contents-spec.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
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
import * as chai from 'chai'
import { AddressInfo } from 'net'
import * as chaiAsPromised from 'chai-as-promised'
import * as path from 'path'
import * as http from 'http'
import { BrowserWindow, ipcMain, webContents, session } from 'electron'
import { emittedOnce } from './events-helpers';
import { closeAllWindows } from './window-helpers';
import { ifdescribe } from './spec-helpers';
const { expect } = chai
chai.use(chaiAsPromised)
const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures')
const features = process.electronBinding('features')
describe('webContents module', () => {
describe('getAllWebContents() API', () => {
afterEach(closeAllWindows)
it('returns an array of web contents', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { webviewTag: true }
})
w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html'))
await emittedOnce(w.webContents, 'did-attach-webview')
w.webContents.openDevTools()
await emittedOnce(w.webContents, 'devtools-opened')
const all = webContents.getAllWebContents().sort((a, b) => {
return a.id - b.id
})
expect(all).to.have.length(3)
expect(all[0].getType()).to.equal('window')
expect(all[all.length - 2].getType()).to.equal('webview')
expect(all[all.length - 1].getType()).to.equal('remote')
})
})
describe('will-prevent-unload event', () => {
afterEach(closeAllWindows)
it('does not emit if beforeunload returns undefined', (done) => {
const w = new BrowserWindow({show: false})
w.once('closed', () => done())
w.webContents.once('will-prevent-unload', (e) => {
expect.fail('should not have fired')
})
w.loadFile(path.join(fixturesPath, 'api', 'close-beforeunload-undefined.html'))
})
it('emits if beforeunload returns false', (done) => {
const w = new BrowserWindow({show: false})
w.webContents.once('will-prevent-unload', () => done())
w.loadFile(path.join(fixturesPath, 'api', 'close-beforeunload-false.html'))
})
it('supports calling preventDefault on will-prevent-unload events', (done) => {
const w = new BrowserWindow({show: false})
w.webContents.once('will-prevent-unload', event => event.preventDefault())
w.once('closed', () => done())
w.loadFile(path.join(fixturesPath, 'api', 'close-beforeunload-false.html'))
})
})
describe('webContents.send(channel, args...)', () => {
afterEach(closeAllWindows)
it('throws an error when the channel is missing', () => {
const w = new BrowserWindow({show: false})
expect(() => {
(w.webContents.send as any)()
}).to.throw('Missing required channel argument')
expect(() => {
w.webContents.send(null as any)
}).to.throw('Missing required channel argument')
})
it('does not block node async APIs when sent before document is ready', (done) => {
// Please reference https://github.com/electron/electron/issues/19368 if
// this test fails.
ipcMain.once('async-node-api-done', () => {
done()
})
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
sandbox: false,
contextIsolation: false
}
})
w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html'))
setTimeout(() => {
w.webContents.send("test")
}, 50)
})
})
ifdescribe(features.isPrintingEnabled())('webContents.print()', () => {
it('throws when invalid settings are passed', () => {
const w = new BrowserWindow({ show: false })
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print(true)
}).to.throw('webContents.print(): Invalid print settings specified.')
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({}, true)
}).to.throw('webContents.print(): Invalid optional callback provided.')
})
it('does not crash', () => {
const w = new BrowserWindow({ show: false })
expect(() => {
w.webContents.print({ silent: true })
}).to.not.throw()
})
})
describe('webContents.executeJavaScript', () => {
describe('in about:blank', () => {
const expected = 'hello, world!'
const expectedErrorMsg = 'woops!'
const code = `(() => "${expected}")()`
const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`
const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`
const errorTypes = new Set([
Error,
ReferenceError,
EvalError,
RangeError,
SyntaxError,
TypeError,
URIError
])
let w: BrowserWindow
before(async () => {
w = new BrowserWindow({show: false})
await w.loadURL('about:blank')
})
after(closeAllWindows)
it('resolves the returned promise with the result', async () => {
const result = await w.webContents.executeJavaScript(code)
expect(result).to.equal(expected)
})
it('resolves the returned promise with the result if the code returns an asyncronous promise', async () => {
const result = await w.webContents.executeJavaScript(asyncCode)
expect(result).to.equal(expected)
})
it('rejects the returned promise if an async error is thrown', async () => {
await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg)
})
it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
for (const error of errorTypes) {
await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`))
.to.eventually.be.rejectedWith(error)
}
})
})
describe("on a real page", () => {
let w: BrowserWindow
beforeEach(() => {
w = new BrowserWindow({show: false})
})
afterEach(closeAllWindows)
let server: http.Server = null as unknown as http.Server
let serverUrl: string = null as unknown as string
before((done) => {
server = http.createServer((request, response) => {
response.end()
}).listen(0, '127.0.0.1', () => {
serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port
done()
})
})
after(() => {
server.close()
})
it('works after page load and during subframe load', (done) => {
w.webContents.once('did-finish-load', () => {
// initiate a sub-frame load, then try and execute script during it
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/slow'
document.body.appendChild(iframe)
`).then(() => {
w.webContents.executeJavaScript('console.log(\'hello\')').then(() => {
done()
})
})
})
w.loadURL(serverUrl)
})
it('executes after page load', (done) => {
w.webContents.executeJavaScript(`(() => "test")()`).then(result => {
expect(result).to.equal("test")
done()
})
w.loadURL(serverUrl)
})
it('works with result objects that have DOM class prototypes', (done) => {
w.webContents.executeJavaScript('document.location').then(result => {
expect(result.origin).to.equal(serverUrl)
expect(result.protocol).to.equal('http:')
done()
})
w.loadURL(serverUrl)
})
})
})
describe('login event', () => {
afterEach(closeAllWindows)
let server: http.Server
let serverUrl: string
let serverPort: number
let proxyServer: http.Server
let proxyServerPort: number
before((done) => {
server = http.createServer((request, response) => {
if (request.url === '/no-auth') {
return response.end('ok')
}
if (request.headers.authorization) {
response.writeHead(200, { 'Content-type': 'text/plain' })
return response.end(request.headers.authorization)
}
response
.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
.end('401')
}).listen(0, '127.0.0.1', () => {
serverPort = (server.address() as AddressInfo).port
serverUrl = `http://127.0.0.1:${serverPort}`
done()
})
})
before((done) => {
proxyServer = http.createServer((request, response) => {
if (request.headers['proxy-authorization']) {
response.writeHead(200, { 'Content-type': 'text/plain' })
return response.end(request.headers['proxy-authorization'])
}
response
.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' })
.end()
}).listen(0, '127.0.0.1', () => {
proxyServerPort = (proxyServer.address() as AddressInfo).port
done()
})
})
afterEach(async () => {
await session.defaultSession.clearAuthCache({ type: 'password' })
})
after(() => {
server.close()
proxyServer.close()
})
it('is emitted when navigating', async () => {
const [user, pass] = ['user', 'pass']
const w = new BrowserWindow({ show: false })
let eventRequest: any
let eventAuthInfo: any
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request
eventAuthInfo = authInfo
event.preventDefault()
cb(user, pass)
})
await w.loadURL(serverUrl)
const body = await w.webContents.executeJavaScript(`document.documentElement.textContent`)
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`)
expect(eventRequest.url).to.equal(serverUrl + '/')
expect(eventAuthInfo.isProxy).to.be.false('is proxy')
expect(eventAuthInfo.scheme).to.equal('basic')
expect(eventAuthInfo.host).to.equal('127.0.0.1')
expect(eventAuthInfo.port).to.equal(serverPort)
expect(eventAuthInfo.realm).to.equal('Foo')
})
it('is emitted when a proxy requests authorization', async () => {
const customSession = session.fromPartition(`${Math.random()}`)
await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' } as any)
const [user, pass] = ['user', 'pass']
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } })
let eventRequest: any
let eventAuthInfo: any
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request
eventAuthInfo = authInfo
event.preventDefault()
cb(user, pass)
})
await w.loadURL(`${serverUrl}/no-auth`)
const body = await w.webContents.executeJavaScript(`document.documentElement.textContent`)
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`)
expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`)
expect(eventAuthInfo.isProxy).to.be.true('is proxy')
expect(eventAuthInfo.scheme).to.equal('basic')
expect(eventAuthInfo.host).to.equal('127.0.0.1')
expect(eventAuthInfo.port).to.equal(proxyServerPort)
expect(eventAuthInfo.realm).to.equal('Foo')
})
it('cancels authentication when callback is called with no arguments', async () => {
const w = new BrowserWindow({ show: false })
w.webContents.on('login', (event, request, authInfo, cb) => {
event.preventDefault()
cb()
})
await w.loadURL(serverUrl)
const body = await w.webContents.executeJavaScript(`document.documentElement.textContent`)
expect(body).to.equal('401')
})
})
it('emits a cancelable event before creating a child webcontents', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
})
w.webContents.on('-will-add-new-contents' as any, (event: any, url: any) => {
expect(url).to.equal('about:blank')
event.preventDefault()
})
let wasCalled = false
w.webContents.on('new-window' as any, () => {
wasCalled = true
})
await w.loadURL('about:blank')
await w.webContents.executeJavaScript(`window.open('about:blank')`)
await new Promise((resolve) => { process.nextTick(resolve) })
expect(wasCalled).to.equal(false)
await closeAllWindows()
})
})