Skip to content

Commit e8a4ee4

Browse files
authored
fix: escape scripts in addInitScript (webdriverio#14717)
If the script passed to addInitScript contains template literals then we'll run into problems where we try to embed it in another template literal hence we need to escape the script first. The E2E test added in this patch fails without the corresponding code change.
1 parent ca92ac8 commit e8a4ee4

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

e2e/wdio/headless/test.e2e.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,25 @@ describe('main suite 1', () => {
430430
expect(await browser.execute(() => Math.random())).not.toBe(42)
431431
})
432432

433+
it('should escape the init script', async () => {
434+
type WindowWithHello = Window & {
435+
sayHello?: (name: string) => string;
436+
}
437+
const script = await browser.addInitScript(() => {
438+
(window as WindowWithHello).sayHello = (name) =>
439+
`Hello ${name}`
440+
})
441+
442+
await browser.url('https://webdriver.io')
443+
expect(
444+
await browser.execute(() =>
445+
(window as WindowWithHello).sayHello!('there'),
446+
),
447+
).toBe('Hello there')
448+
449+
await script.remove()
450+
})
451+
433452
it('passed on callback function', async () => {
434453
const script = await browser.addInitScript((num, str, bool, emit) => {
435454
setTimeout(() => emit(JSON.stringify([num, str, bool])), 500)

packages/webdriverio/src/commands/browser/addInitScript.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,9 @@ export async function addInitScript<Payload, Arg1, Arg2, Arg3, Arg4, Arg5> (
113113

114114
const serializedParameters = (args || []).map((arg: unknown) => JSON.stringify(arg))
115115
const context = await this.getWindowHandle()
116+
const src = 'return ' + script.toString()
116117
const fn = `(emit) => {
117-
const closure = new Function(\`return ${script.toString()}\`)
118+
const closure = new Function(${JSON.stringify(src)})
118119
return closure()(${serializedParameters.length ? `${serializedParameters.join(', ')}, emit` : 'emit'})
119120
}`
120121
const channel = btoa(fn.toString())

0 commit comments

Comments
 (0)