Page
Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.
This example creates a page, navigates it to a URL, and then saves a screenshot:
playwright.webkit.launch do |browser|
page = browser.new_page
page.goto('https://example.com/')
page.screenshot(path: 'screenshot.png')
end
The Page class emits various events (described below) which can be handled using any of Node's native
EventEmitter methods, such as on, once or
removeListener.
This example logs a message for a single page load event:
page.once("load", -> (page) { puts "page loaded!" })
To unsubscribe from events use the removeListener method:
listener = -> (req) { puts "a request was made: #{req.url}" }
page.on('request', listener)
page.goto('https://example.com/') # => prints 'a request was made: https://example.com/'
page.off('request', listener)
page.goto('https://example.com/') # => no print
add_init_script
def add_init_script(path: nil, script: nil)
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.
Usage
An example of overriding Math.random before the page loads:
# 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 BrowserContext#add_init_script and Page#add_init_script is not defined.