Method: Playwright::Page#add_init_script

Defined in:
lib/playwright_api/page.rb

#add_init_script(path: nil, script: nil) ⇒ Object

Adds a script which would be evaluated in one of the following scenarios:

  • Whenever the page is navigated.

  • Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.

The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed ‘Math.random`.

An example of overriding ‘Math.random` before the page loads:

“‘js browser // preload.js Math.random = () => 42; “`

“‘js // In your playwright script, assuming the preload.js file is in same directory await page.addInitScript({ path: ’./preload.js’ }); “‘

“‘python async # in your playwright script, assuming the preload.js file is in same directory await page.add_init_script(path=“./preload.js”) “`

“‘python sync # in your playwright script, assuming the preload.js file is in same directory page.add_init_script(path=“./preload.js”) “`

> NOTE: The order of evaluation of multiple scripts installed via [‘method: BrowserContext.addInitScript`] and

‘method: Page.addInitScript`

is not defined.



145
146
147
# File 'lib/playwright_api/page.rb', line 145

def add_init_script(path: nil, script: nil)
  wrap_impl(@impl.add_init_script(path: unwrap_impl(path), script: unwrap_impl(script)))
end