### Install and Setup Playwright Ruby Client Source: https://context7.com/yusukeiwaki/playwright-ruby-client/llms.txt Add the gem to your Gemfile, install the Playwright CLI, and then create a Playwright instance. This example demonstrates launching a headless Chromium browser, navigating to a page, and taking a screenshot. ```ruby # Gemfile gem 'playwright-ruby-client' # Terminal # npm install playwright && npx playwright install require 'playwright' Playwright.create(playwright_cli_executable_path: 'npx playwright') do |playwright| playwright.chromium.launch(headless: true) do |browser| page = browser.new_page page.goto('https://example.com') puts page.title # => "Example Domain" page.screenshot(path: 'example.png') end end ``` -------------------------------- ### Launch Playwright Server Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/README.md Execute this command to install browsers and start the Playwright server on a specified port and path. ```bash npx playwright install && npx playwright run-server --port 8080 --path /ws ``` -------------------------------- ### Usage Example: Start and Stop Tracing Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/browser.md Demonstrates how to start Chromium tracing, navigate to a page, and then stop the tracing to get the trace data. This is useful for performance analysis. ```ruby browser.start_tracing(page: page, path: "trace.json") begin page.goto("https://www.google.com") ensure browser.stop_tracing end ``` -------------------------------- ### CDPSession Usage Example Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/cdp_session.md Demonstrates how to create a CDPSession, send messages to enable CDP domains, subscribe to events, and send messages to get and set playback rates. ```APIDOC ## CDPSession Usage Example ### Description This example shows how to initialize a CDPSession, interact with CDP domains like Animation, and handle responses and events. ### Code ```ruby client = page.context.new_cdp_session(page) client.send_message('Animation.enable') client.on('Animation.animationCreated', -> (_) { puts 'Animation Created' }) response = client.send_message('Animation.getPlaybackRate') puts "Playback rate is #{response['playbackRate']}" client.send_message( 'Animation.setPlaybackRate', params: { playbackRate: response['playbackRate'] / 2.0 }, ) ``` ``` -------------------------------- ### Start Local Development Server Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/README.md Starts a local development server. Changes are reflected live without restarting. ```bash yarn start ``` -------------------------------- ### Install Dependencies Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/README.md Run this command to install project dependencies using Yarn. ```bash yarn install ``` -------------------------------- ### Install Ruby Dependencies Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/development/README.md Run this command to install all necessary Ruby gems for the project. ```sh bin/setup ``` -------------------------------- ### Setup and Test Case Definition Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/name_test_case_721-manual.html Initializes the testing environment and defines a specific test case for verifying the 'name' property. This setup is used for automated accessibility checks. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ ["property", "name", "is", "States:"] ], "AXAPI" : [ ["property", "AXDescription", "is", "States:"] ], "IAccessible2" : [ ["property", "accName", "is", "States:"] ], "UIA" : [ ["property", "Name", "is", "States:"] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name test case 721" } ); ``` -------------------------------- ### Mouse Actions Example Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/mouse.md Example of using the Mouse object to trace a square path. ```APIDOC ## Mouse Actions Example This example demonstrates how to use the `page.mouse` object to simulate a sequence of mouse movements to trace a square. ```ruby # using ‘page.mouse’ to trace a 100x100 square. page.mouse.move(0, 0) page.mouse.down page.mouse.move(0, 100) page.mouse.move(100, 100) page.mouse.move(100, 0) page.mouse.move(0, 0) page.mouse.up ``` ``` -------------------------------- ### Setup and Test Case Definition Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/description_test_case_broken_reference-manual.html Initializes the testing environment and defines a test case for the 'description' property. This setup is used to examine ARIA properties across various accessibility APIs. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "description", "is", "" ] ], "AXAPI" : [ [ "property", "AXHelp", "is", "" ] ], "IAccessible2" : [ [ "property", "accDescription", "is", "" ] ], "UIA" : [ [ "property", "Description", "is", "" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Description test case broken reference" } ); ``` -------------------------------- ### Install Playwright Ruby Client Gem Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/README.md Add the playwright-ruby-client gem to your Gemfile and run 'bundle install'. Ensure Playwright is installed separately. ```ruby gem 'playwright-ruby-client' ``` -------------------------------- ### Install Playwright and Run Tests Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/development/README.md Installs necessary Playwright components and runs the project's RSpec tests. Note that testing with the latest driver might fail due to breaking changes. ```sh $PLAYWRIGHT_CLI_EXECUTABLE_PATH install bundle exec rspec ``` -------------------------------- ### Start Tracing with Options Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/tracing.md Initiates tracing with options for capturing screenshots and snapshots. This is a prerequisite for recording detailed browser interactions. ```ruby context.tracing.start(screenshots: true, snapshots: true) page = context.new_page page.goto('https://playwright.dev') context.tracing.stop(path: 'trace.zip') ``` -------------------------------- ### System Test Example with Native Playwright Methods Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/article/guides/rails_integration_with_null_driver.md An example of a system test using the configured null driver and native Playwright methods. It demonstrates navigating to a page, interacting with elements, and asserting content. ```ruby require 'rails_helper' describe 'example', driver: :null do let!(:user) { FactoryBot.create(:user) } let(:page) { @playwright_page } it 'can browse' do page.goto("/tests/#{user.id}") page.wait_for_selector('input').type('hoge') page.keyboard.press('Enter') expect(page.text_content('#content')).to include('hoge') end end ``` -------------------------------- ### Tracing.start Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/tracing.md Starts recording a trace. Options include enabling screenshots, snapshots, and providing a name or title for the trace. ```APIDOC ## start ```ruby def start( live: nil, name: nil, screenshots: nil, snapshots: nil, sources: nil, title: nil) ``` Start tracing. **Usage** ```ruby context.tracing.start(screenshots: true, snapshots: true) page = context.new_page page.goto('https://playwright.dev') context.tracing.stop(path: 'trace.zip') ``` ``` -------------------------------- ### Install Playwright Driver using npm install Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/article/guides/download_playwright_driver.md A faster alternative to npx for setting up the Playwright driver, suitable for most use cases with an existing Node.js environment. Set `playwright_cli_executable_path` to `'./node_modules/.bin/playwright'`. ```shell $ export PLAYWRIGHT_CLI_VERSION=$(bundle exec ruby -e 'puts Playwright::COMPATIBLE_PLAYWRIGHT_VERSION.strip') $ npm install playwright@$PLAYWRIGHT_CLI_VERSION || npm install playwright@next $ ./node_modules/.bin/playwright install ``` -------------------------------- ### Install Playwright Driver Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/article/getting_started.md Before using the Playwright Ruby client, you must install the Playwright driver. This command downloads the necessary browser binaries. ```shell $ npx playwright install ``` -------------------------------- ### Send GET Request with Query Parameters Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/api_request_context.md Use the `get` method to send an HTTP GET request. Configure URL query parameters using the `params` option, which serializes a hash into the URL's search string. ```ruby query_params = { isbn: "1234", page: "23" } api_request_context.get("https://example.com/api/get_text", params: query_params) ``` -------------------------------- ### Example Usage of Request Timing Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/request.md Demonstrates how to capture a request event and access its timing information. ```ruby request = page.expect_event("requestfinished") do page.goto("https://example.com") end puts request.timing ``` -------------------------------- ### JavaScript Test Case Setup Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/name_test_case_758-manual.html Sets up a test case to verify the accessibility name of an element, considering various accessibility APIs. This setup is used for testing name determination with appended content. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "name", "is", "fancy fruit" ] ], "AXAPI" : [ [ "property", "AXDescription", "is", "fancy fruit" ] ], "IAccessible2" : [ [ "property", "accName", "is", "fancy fruit" ] ], "UIA" : [ [ "property", "Name", "is", "fancy fruit" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name test case 758" } ); ``` -------------------------------- ### Install Playwright Node.js Driver Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/development/README.md Installs the Playwright Node.js driver matching the compatible version specified in the project. Avoid using `npx` as it fetches the latest version. ```sh VERSION=$(ruby -r "./lib/playwright/version" -e "puts Playwright::COMPATIBLE_PLAYWRIGHT_VERSION") npm install "playwright@$VERSION" ``` -------------------------------- ### Trigger select-all shortcut Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/keyboard.md Provides examples for triggering the select-all keyboard shortcut, with platform-specific variations. ```ruby # RECOMMENDED page.keyboard.press("ControlOrMeta+A") # or just on windows and linux page.keyboard.press("Control+A") # or just on macOS page.keyboard.press("Meta+A") ``` -------------------------------- ### APIRequestContext Usage Example Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/api_request_context.md Demonstrates how to create and use an APIRequestContext to interact with API endpoints, including creating and deleting repositories. ```APIDOC ## APIRequestContext Usage Example This example shows how to use `APIRequestContext` to interact with the GitHub API. ### Method ```ruby playwright.chromium.launch do |browser| context = browser.new_context(base_url: 'https://api.github,com') api_request_context = context.request # Create a repository. response = api_request_context.post( "/user/repos", headers: { "Accept": "application/vnd.github.v3+json", "Authorization": "Bearer #{API_TOKEN}", }, data: { name: 'test-repo-1' }, ) response.ok? # => true response.json['name'] # => "test-repo-1" # Delete a repository. response = api_request_context.delete( "/repos/YourName/test-repo-1", headers: { "Accept": "application/vnd.github.v3+json", "Authorization": "Bearer #{API_TOKEN}", }, ) response.ok? # => true end ``` ``` -------------------------------- ### Tracing.start_chunk Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/tracing.md Starts a new trace chunk. This is useful for recording multiple traces within the same BrowserContext. ```APIDOC ## start_chunk ```ruby def start_chunk(name: nil, title: nil) ``` Start a new trace chunk. If you'd like to record multiple traces on the same [BrowserContext](./browser_context), use [Tracing#start](./tracing#start) once, and then create multiple trace chunks with [Tracing#start_chunk](./tracing#start_chunk) and [Tracing#stop_chunk](./tracing#stop_chunk). **Usage** ```ruby context.tracing.start(screenshots: true, snapshots: true) page = context.new_page page.goto("https://playwright.dev") context.tracing.start_chunk page.get_by_text("Get Started").click # Everything between start_chunk and stop_chunk will be recorded in the trace. context.tracing.stop_chunk(path: "trace1.zip") context.tracing.start_chunk page.goto("http://example.com") # Save a second trace file with different actions. context.tracing.stop_chunk(path: "trace2.zip") ``` ``` -------------------------------- ### Full Device Emulation via Context Source: https://context7.com/yusukeiwaki/playwright-ruby-client/llms.txt Launches a browser and creates a new context emulating a specific device, then navigates to a URL and prints the viewport size. ```ruby Playwright.create(playwright_cli_executable_path: 'npx playwright') do |playwright| pixel5 = playwright.devices["Pixel 5"] playwright.chromium.launch do |browser| browser.new_context(**pixel5) do |context| page = context.new_page page.goto('https://example.com') puts page.viewport_size # => {"width"=>393, "height"=>851} end end end ``` -------------------------------- ### Setup and Test Case Initialization Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/description_test_case_774-manual.html Initializes the test environment with explicit timeouts and done callbacks, then defines a test case using ATTAcomm to verify the 'description' property across various accessibility APIs. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "description", "is", "foo" ] ], "AXAPI" : [ [ "property", "AXHelp", "is", "foo" ] ], "IAccessible2" : [ [ "property", "accDescription", "is", "foo" ] ], "UIA" : [ [ "property", "Description", "is", "foo" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Description test case 774" } ); ``` -------------------------------- ### Android Native Automation Example Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/article/getting_started.md Interacts with an Android device at a native level, simulating key presses and tapping on UI elements. This requires the Android driver to be downloaded and installed. ```ruby require 'playwright' Playwright.create(playwright_cli_executable_path: ENV['PLAYWRIGHT_CLI_EXECUTABLE_PATH']) do |playwright| devices = playwright.android.devices unless devices.empty? device = devices.last begin device.shell('input keyevent POWER') device.shell('input keyevent POWER') device.shell('input keyevent 82') sleep 1 device.shell('cmd statusbar expand-notifications') # pp device.tree # pp device.info(res: 'com.android.systemui:id/clock') device.tap_on(res: 'com.android.systemui:id/clock') ensure device.close end end end ``` -------------------------------- ### Connect to Remote Playwright Server Source: https://context7.com/yusukeiwaki/playwright-ruby-client/llms.txt Connect to a running remote Playwright server over WebSocket. No local Playwright CLI installation is required for this method. Ensure the server is started with the correct port and path. ```ruby require 'playwright' # Start server with: npx playwright run-server --port 8080 --path /ws Playwright.connect_to_browser_server('ws://localhost:8080/ws') do |browser| page = browser.new_page page.goto('https://example.com') page.screenshot(path: 'remote.png') puts browser.version end ``` -------------------------------- ### Enable Chrome Extensions in Playwright Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/article/guides/semi_automation.md To work with Chrome extensions, enable the feature by passing `acceptDownloads: true`, `channel: 'chrome'`, `headless: false`, and `ignoreDefaultArgs: ['--disable-extensions']` when launching a persistent context. This example also includes setup for Playwright and Pry. ```ruby require 'playwright' require 'pry' Playwright.create(playwright_cli_executable_path: './node_modules/.bin/playwright') do |playwright| launch_params = { acceptDownloads: true, channel: 'chrome', headless: false, ignoreDefaultArgs: ['--disable-extensions'], } playwright.chromium.launch_persistent_context('./data/', **launch_params) do |context| page = context.new_page page.goto('https://example.com/') binding.pry end end ``` -------------------------------- ### Get Download Path Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/download.md Returns the local file system path of a successfully downloaded file. This method waits for the download to finish. It throws an error for failed or canceled downloads and may throw when connected remotely. The actual filename is a GUID; use `suggested_filename` for the user-friendly name. ```ruby def path end ``` -------------------------------- ### Basic GET Request Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/network-tab/network.html A simple GET request to an API endpoint. ```javascript fetch('/api/endpoint') ``` -------------------------------- ### Start and Stop Tracing Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/tracing.md Use `context.tracing.start` to begin recording and `context.tracing.stop` to save the trace to a file. This method captures browser operations and network activity. ```ruby browser.new_context do |context| context.tracing.start(screenshots: true, snapshots: true) page = context.new_page page.goto('https://playwright.dev') context.tracing.stop(path: 'trace.zip') end ``` -------------------------------- ### Launch and Use Browser Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/browser.md Launches a browser, creates a new page, navigates to a URL, and ensures the browser is closed. ```ruby firefox = playwright.firefox browser = firefox.launch begin page = browser.new_page page.goto("https://example.com") ensure browser.close end ``` -------------------------------- ### Setup and Test Case Initialization Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/description_test_case_666-manual.html Initializes the test environment with explicit timeouts and defines a test case for checking the 'description' property across various accessibility APIs. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "description", "is", "foo" ] ], "AXAPI" : [ [ "property", "AXHelp", "is", "foo" ] ], "IAccessible2" : [ [ "property", "accDescription", "is", "foo" ] ], "UIA" : [ [ "property", "Description", "is", "foo" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Description test case 666" } ); ``` -------------------------------- ### GET Request with Query Parameters Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/network-tab/network.html A GET request including query parameters, with duplicate parameter names allowed. ```javascript fetch('/call-with-query-params?param1=value1¶m1=value2¶m2=value2') ``` -------------------------------- ### goto Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/frame.md Navigates to the specified URL. ```APIDOC ## goto ```ruby def goto(url, referer: nil, timeout: nil, waitUntil: nil) ``` ### Description Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. The method will throw an error if: - there's an SSL error (e.g. in case of self-signed certificates). - target URL is invalid. - the `timeout` is exceeded during navigation. - the remote server does not respond or is unreachable. - the main resource failed to load. The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [Response#status](./response#status). **NOTE**: The method either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`. **NOTE**: Headless mode doesn't support navigation to a PDF document. See the [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295). ### Parameters #### Path Parameters - **url** (string) - Required - The URL to navigate to. - **referer** (string) - Optional - The referer URL. - **timeout** (number) - Optional - Maximum navigation time in milliseconds. - **waitUntil** (string) - Optional - When to consider navigation successful, one of `load`, `domcontentloaded`, `networkidle`, `commit`. Defaults to `load`. ``` -------------------------------- ### GET Request Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/api_request_context.md Sends an HTTP GET request and returns its response. Cookies are managed automatically, and redirects are followed. ```APIDOC ## GET /api/get ### Description Sends an HTTP(S) GET request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects. ### Method GET ### Endpoint /api/get ### Parameters #### Query Parameters - **params** (object) - Optional - Request parameters serialized into URL search parameters. - **url** (string) - Required - The URL to send the GET request to. - **data** (any) - Optional - Request body data. - **failOnStatusCode** (boolean) - Optional - Whether to fail if the status code is not successful. - **form** (object) - Optional - Form data to be sent in the request body. - **headers** (object) - Optional - Custom headers to send with the request. - **ignoreHTTPSErrors** (boolean) - Optional - Whether to ignore HTTPS errors. - **maxRedirects** (number) - Optional - Maximum number of redirects to follow. - **maxRetries** (number) - Optional - Maximum number of retries for the request. - **multipart** (object) - Optional - Multipart data for file uploads. - **timeout** (number) - Optional - Request timeout in milliseconds. ### Request Example ```ruby query_params = { isbn: "1234", page: "23" } api_request_context.get("https://example.com/api/get_text", params: query_params) ``` ``` -------------------------------- ### Mount Main Application (Vue.js) Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/reading-list/vue2.html Initializes and mounts the main Vue application. It sets up the root element, defines the main template, and initializes the 'books' data. It also includes methods for adding new books and mounting nested applications. ```javascript window.mountApp = element => new Vue({ el: element, template: `
`, data() { return { books: [ {name: 'Pride and Prejudice' }, {name: 'To Kill a Mockingbird' }, {name: 'The Great Gatsby' }, ], }; }, methods: { addNewBook(name) { console.log('here'); this.books.push({name}); } }, }); window.app = window.mountApp(document.querySelector('#root div')); window.mountNestedApp = () => window.mountApp(window.app.$refs.mountPoint); ``` -------------------------------- ### Initializing and Mounting Nested App Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/reading-list/react15.html Initializes the main application and provides a way to mount a nested application within the main app's mount point. Useful for complex component hierarchies. ```javascript window.app = window.mountApp(document.getElementById('root')); window.mountNestedApp = () => window.mountApp(window.app.root.refs.mountPoint); ``` -------------------------------- ### Clock#install Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/clock.md Installs fake implementations for various time-related functions, allowing manual control over time flow in tests. ```APIDOC ## install ### Description Install fake implementations for the following time-related functions: - `Date` - `setTimeout` - `clearTimeout` - `setInterval` - `clearInterval` - `requestAnimationFrame` - `cancelAnimationFrame` - `requestIdleCallback` - `cancelIdleCallback` - `performance` Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers, and control the behavior of time-dependent functions. See [Clock#run_for](./clock#run_for) and [Clock#fast_forward](./clock#fast_forward) for more information. ### Method `install(time: nil)` ### Parameters #### Path Parameters - **time** (Time | string) - Optional - The initial time to set the clock to. If nil, the current system time is used. ``` -------------------------------- ### Install Playwright Driver Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/README.md Install the Playwright Node.js package and its driver. Alternatively, download the driver directly from the provided URL. ```sh npm install playwright ./node_modules/.bin/playwright install ``` -------------------------------- ### BrowserType#launch Source: https://context7.com/yusukeiwaki/playwright-ruby-client/llms.txt Launches a new browser instance. Accepts options for headless mode, slow-motion, browser channel, proxy, and more. Yields a `Browser` object and closes it automatically when the block exits. ```APIDOC ## BrowserType#launch Launches a new browser instance. Accepts options for headless mode, slow-motion, browser channel, proxy, and more. Yields a `Browser` object and closes it automatically when the block exits. ### Method ```ruby Playwright.create(playwright_cli_executable_path: 'npx playwright') do |playwright| playwright.chromium.launch( headless: false, slowMo: 50, channel: 'chrome' # Use installed Google Chrome ) do |browser| page = browser.new_page page.goto('https://example.com') puts browser.version puts browser.connected? # => true end end ``` ``` -------------------------------- ### Playwright.create with Device Emulation Source: https://context7.com/yusukeiwaki/playwright-ruby-client/llms.txt Use Playwright.create to initialize the Playwright instance. This example shows how to use a device preset for mobile emulation and interact with different browser types. ```ruby require 'playwright' Playwright.create(playwright_cli_executable_path: 'npx playwright') do |playwright| # Use a device preset for mobile emulation iphone = playwright.devices["iPhone 13"] playwright.webkit.launch(headless: true) do |browser| context = browser.new_context(**iphone) page = context.new_page page.goto('https://example.com') puts page.viewport_size # => {"width"=>390, "height"=>844} puts playwright.chromium.name # => "chromium" puts playwright.firefox.name # => "firefox" end end ``` -------------------------------- ### Record Video to a Temporary Directory Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/article/guides/recording_video.md Launches a browser, creates a new context with video recording enabled in a temporary directory, and retrieves the video path. The video is fully saved after the browser context is closed. ```ruby require 'tmpdir' playwright.chromium.launch do |browser| Dir.mktmpdir do |tmp| video_path = nil browser.new_context(record_video_dir: tmp) do |context| page = context.new_page # play with page # NOTE: Page#video is available **only when browser context is alive.** video_path = page.video.path end # NOTE: video is completely saved **only after browser context is closed.** handle_video_as_you_like(video_path) end end ``` -------------------------------- ### API Request Context GET Method Signature Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/api_request_context.md Signature for the `get` method in the API request context. It supports various options for configuring the HTTP request. ```ruby def get( url, data: nil, failOnStatusCode: nil, form: nil, headers: nil, ignoreHTTPSErrors: nil, maxRedirects: nil, maxRetries: nil, multipart: nil, params: nil, timeout: nil) ``` -------------------------------- ### JavaScript Function Example Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/jscoverage/involved.html Demonstrates basic JavaScript conditional logic, ternary operators, and arrow functions. This example is for illustrative purposes and does not involve Playwright-specific functionality. ```javascript function foo() { if (1 > 2) console.log(1); if (1 < 2) console.log(2); let x = 1 > 2 ? 'foo' : 'bar'; let y = 1 < 2 ? 'foo' : 'bar'; let z = () => {}; let q = () => {}; q(); } foo(); ``` -------------------------------- ### Playwright Ruby Search Results Example Output Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/README.md Example output from the simple scraping script, showing the titles of repositories found during a Playwright search on GitHub. ```sh $ bundle exec ruby main.rb ==> microsoft/playwright ==> microsoft/playwright-python ==> microsoft/playwright-cli ==> checkly/headless-recorder ==> microsoft/playwright-sharp ==> playwright-community/jest-playwright ==> microsoft/playwright-test ==> mxschmitt/playwright-go ==> microsoft/playwright-java ==> MarketSquare/robotframework-browser ``` -------------------------------- ### Create New Browser Context and Page Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/browser.md Launches a browser and creates a new incognito browser context, then a new page within that context. ```ruby playwright.firefox.launch do |browser| # or "chromium.launch" or "webkit.launch". # create a new incognito browser context. browser.new_context do |context| # create a new page in a pristine context. page = context.new_page page.goto("https://example.com") end end ``` -------------------------------- ### Get input element value Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/frame.md Use `input_value` to get the `value` of an input, textarea, or select element. It also handles associated controls within a label element. ```ruby def input_value(selector, strict: nil, timeout: nil) ``` -------------------------------- ### Browser#new_context with Configuration Source: https://context7.com/yusukeiwaki/playwright-ruby-client/llms.txt Creates an isolated browser context with independent cookies and storage. This example configures viewport, locale, timezone, geolocation, permissions, and video recording. ```ruby browser.new_context( viewport: { width: 1280, height: 720 }, locale: 'en-US', timezoneId: 'America/New_York', geolocation: { latitude: 40.7128, longitude: -74.0060 }, permissions: ['geolocation'], ignoreHTTPSErrors: true, record_video_dir: './videos/' ) do |context| page = context.new_page page.goto('https://maps.example.com') # Video is saved automatically when the context closes end ``` -------------------------------- ### Start and Stop Playwright Session Separately Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/article/guides/launch_browser.md Allows defining the start and end of a Playwright session separately. Ensure `PlaywrightExecution#stop` is called to properly terminate the driver. ```ruby class SomeClass def start_playwright # Start Playwright driver (runs `playwright run-driver` internally) @playwright_exec = Playwright.create(playwright_cli_executable_path: 'npx playwright') end def stop_playwright! # Stop Playwright driver @playwright_exec.stop end def play_with_playwright(&blk) # Acquire Playwright instance with PlaywrightExecution#playwright playwright = @playwright_exec.playwright browser = playwright.chromium.launch begin blk.call(browser) ensure browser.close end end end ``` -------------------------------- ### Navigate to URL with Page#goto Source: https://context7.com/yusukeiwaki/playwright-ruby-client/llms.txt Navigates the page to a URL and returns the main resource response. Supports various `waitUntil` options and custom timeouts. ```ruby response = page.goto('https://example.com', waitUntil: 'networkidle', timeout: 30_000) puts response.status # => 200 puts response.ok? # => true puts page.url # => "https://example.com/" puts page.title # => "Example Domain" ``` -------------------------------- ### Build Static Content Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/README.md Generates static content for deployment. The output is placed in the 'build' directory. ```bash yarn build ``` -------------------------------- ### Create Page, Navigate, and Screenshot Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/page.md Launches a browser, creates a new page, navigates to a URL, and saves a screenshot. Ensure Playwright is installed and configured. ```ruby playwright.webkit.launch do |browser| page = browser.new_page page.goto('https://example.com/') page.screenshot(path: 'screenshot.png') end ``` -------------------------------- ### BrowserType#launch with Options Source: https://context7.com/yusukeiwaki/playwright-ruby-client/llms.txt Launches a new browser instance with specified options such as headless mode, slow-motion, and browser channel. The browser is automatically closed when the block finishes. ```ruby Playwright.create(playwright_cli_executable_path: 'npx playwright') do |playwright| playwright.chromium.launch( headless: false, slowMo: 50, channel: 'chrome' # Use installed Google Chrome ) do |browser| page = browser.new_page page.goto('https://example.com') puts browser.version puts browser.connected? # => true end end ``` -------------------------------- ### Strict Frame Locator Usage Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/frame_locator.md Demonstrates strictness in FrameLocators. The first example throws an error if multiple frames match '.result-frame'. The second example explicitly selects the first matching frame. ```ruby # Throws if there are several frames in DOM: page.locator('.result-frame').content_frame.get_by_role('button').click ``` ```ruby # Works because we explicitly tell locator to pick the first frame: page.locator('.result-frame').first.content_frame.get_by_role('button').click ``` -------------------------------- ### Initializing and Mounting Nested React App Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/reading-list/react16.html Initializes the main React app and provides a function to mount a nested app using the mount point from the main app's root. ```javascript window.app = window.mountApp(document.getElementById('root')); window.mountNestedApp = () => window.mountApp(window.app.root.mountPoint.current); ``` -------------------------------- ### Install Clock Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/clock.md Install fake implementations for time-related functions like Date, setTimeout, setInterval, and performance. Fake timers control the flow of time in tests, allowing manual advancement and timer firing. ```ruby # Fake timers are used to manually control the flow of time in tests. # They allow you to advance time, fire timers, and control the behavior of time-dependent functions. See [Clock#run_for](./clock#run_for) and [Clock#fast_forward](./clock#fast_forward) for more information. ``` -------------------------------- ### Initialize Test Case with ARIA Properties Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/description_test_case_557-manual.html Sets up the test environment and defines the test case structure, including steps to verify the 'description' property using ARIA, IAccessible2, and UIA. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "description", "is", "t" ] ], "AXAPI" : [ [ "property", "AXHelp", "is", "t" ] ], "IAccessible2" : [ [ "property", "accDescription", "is", "t" ] ], "UIA" : [ [ "property", "Description", "is", "t" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Description test case 557" } ); ``` -------------------------------- ### Rails System Spec Example Source: https://context7.com/yusukeiwaki/playwright-ruby-client/llms.txt Demonstrates a typical RSpec system spec using the Playwright driver, including setting up trace saving and performing basic interactions like visiting pages, filling forms, and clicking buttons. ```ruby # In RSpec system spec RSpec.describe "User login", type: :system do before do # Save trace for debugging failures Capybara.current_session.driver.on_save_trace do |trace_zip| attach_file(trace_zip, "trace-#{example.description}.zip") end end it "logs in successfully" do visit "/login" fill_in "Email", with: "user@example.com" fill_in "Password", with: "secret" click_button "Sign in" expect(page).to have_text("Dashboard") end it "uses Playwright-native API for complex interactions" do visit "/editor" Capybara.current_session.driver.with_playwright_page do |pw_page| pw_page.get_by_role("button", name: "Bold").click pw_page.keyboard.type("Hello World") pw_page.screenshot(path: "editor_state.png") end end end ``` -------------------------------- ### Setup and ARIA Name Test Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/name_from_content-manual.html Initializes the testing environment and defines a test case for ARIA name calculation from content. This setup is used to verify accessibility name properties across different platforms. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "name", "is", "My name is Eli the weird. (QED) Where are my marbles?" ] ], "AXAPI" : [ [ "property", "AXDescription", "is", "My name is Eli the weird. (QED) Where are my marbles?" ] ], "IAccessible2" : [ [ "property", "accName", "is", "My name is Eli the weird. (QED) Where are my marbles?" ] ], "UIA" : [ [ "property", "Name", "is", "My name is Eli the weird. (QED) Where are my marbles?" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name from content" } ); ``` -------------------------------- ### url Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/page.md Gets the current URL of the page. ```APIDOC ## url ```ruby def url ``` ``` -------------------------------- ### JavaScript Test Case Setup Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/description_test_case_772-manual.html Sets up a test case for accessibility descriptions using a custom ATTAcomm object. It configures explicit timeouts and done callbacks. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "description", "is", "foo" ] ], "AXAPI" : [ [ "property", "AXHelp", "is", "foo" ] ], "IAccessible2" : [ [ "property", "accDescription", "is", "foo" ] ], "UIA" : [ [ "property", "Description", "is", "foo" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Description test case 772" } ); ``` -------------------------------- ### Name Test Case 740 Setup Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/name_test_case_740-manual.html Initializes the test environment with explicit timeouts and done callbacks. Defines a test case named 'Name test case 740' with a single step. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "name", "is", "crazy Monday" ] ], "AXAPI" : [ [ "property", "AXDescription", "is", "crazy Monday" ] ], "IAccessible2" : [ [ "property", "accName", "is", "crazy Monday" ] ], "UIA" : [ [ "property", "Name", "is", "crazy Monday" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name test case 740" } ); ``` -------------------------------- ### Setup and Test Case Definition for ARIA Name Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/name_test_case_614-manual.html Initializes the test environment and defines a test case for verifying the 'name' property using various accessibility APIs. This setup is used for ARIA Name Test Case 614. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "name", "is", "foo" ] ], "AXAPI" : [ [ "property", "AXDescription", "is", "foo" ] ], "IAccessible2" : [ [ "property", "accName", "is", "foo" ] ], "UIA" : [ [ "property", "Name", "is", "foo" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name test case 614" } ); ``` -------------------------------- ### Get Frame Title Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/frame.md Returns the title of the frame. ```ruby def title end ``` -------------------------------- ### Deploy to GitHub Pages Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/README.md Builds the website and pushes it to the 'gh-pages' branch for GitHub Pages hosting. Ensure your GitHub username and SSH usage are configured. ```bash GIT_USER= USE_SSH=true yarn deploy ``` -------------------------------- ### Get Text Content Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/element_handle.md Returns the node.textContent of the element. ```ruby def text_content ``` -------------------------------- ### Get Worker URL Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/worker.md Retrieves the URL of the worker. ```ruby def url ``` ``` -------------------------------- ### Page#goto Source: https://context7.com/yusukeiwaki/playwright-ruby-client/llms.txt Navigates the page to a URL and returns the main resource response. Supports `waitUntil` values: `"load"` (default), `"domcontentloaded"`, `"networkidle"`, `"commit"`. ```APIDOC ## Page#goto Navigates the page to a URL and returns the main resource response. Supports `waitUntil` values: `"load"` (default), `"domcontentloaded"`, `"networkidle"`, `"commit"`. ```ruby response = page.goto('https://example.com', waitUntil: 'networkidle', timeout: 30_000) puts response.status # => 200 puts response.ok? # => true puts page.url # => "https://example.com/" puts page.title # => "Example Domain" ``` ``` -------------------------------- ### Get Request URL Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/request.md Retrieves the URL of the network request. ```ruby def url ``` -------------------------------- ### content Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/frame.md Gets the full HTML contents of the frame, including the doctype. ```APIDOC ## content Gets the full HTML contents of the frame, including the doctype. ### Returns * `string` - The HTML content of the frame. ``` -------------------------------- ### Navigate to URL Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/frame.md The `goto` method navigates the page to a specified URL. It returns the main resource response and handles redirects. Errors are thrown for SSL issues, invalid URLs, timeouts, or server unreachability. Valid HTTP status codes are not considered errors. ```ruby def goto(url, referer: nil, timeout: nil, waitUntil: nil) ``` -------------------------------- ### Combobox Focusable Description Test Setup Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/description_1.0_combobox-focusable-manual.html Sets up the test environment with explicit timeouts and initializes the test case for a combobox, defining steps to check its description property via various accessibility APIs. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "description", "is", "" ] ], "AXAPI" : [ [ "property", "AXHelp", "is", "" ] ], "IAccessible2" : [ [ "property", "accDescription", "is", "" ] ], "UIA" : [ [ "property", "Description", "is", "" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Description 1.0 combobox-focusable" } ); ``` -------------------------------- ### Get Security Details Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/response.md Retrieves SSL and other security-related information for the response. ```ruby def security_details end ``` -------------------------------- ### Launch Browser Separately Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/article/guides/launch_browser.md Launch a browser instance and manually close it using `Browser#close` within a `ensure` block to guarantee closure. ```ruby # separated start/end browser = playwright.chromium.launch begin # Play with `@browser` ensure browser.close end ``` -------------------------------- ### Get Matching Request Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/response.md Retrieves the Request object that corresponds to this response. ```ruby def request end ``` -------------------------------- ### Get HTTP Version Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/response.md Retrieves the HTTP version used by the response. ```ruby def http_version end ``` -------------------------------- ### ARIA Name Test Case 545 Setup Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/spec/assets/wpt/accname/manual/name_test_case_545-manual.html Sets up the test environment with explicit timeouts and done callbacks. Initializes a new ATTAcomm object with test steps. ```javascript setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "name", "is", "foo" ] ], "AXAPI" : [ [ "property", "AXDescription", "is", "foo" ] ], "IAccessible2" : [ [ "property", "accName", "is", "foo" ] ], "UIA" : [ [ "property", "Name", "is", "foo" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name test case 545" } ); ``` -------------------------------- ### Get Initiating Frame Source: https://github.com/yusukeiwaki/playwright-ruby-client/blob/main/documentation/docs/api/response.md Retrieves the Frame object that initiated this response. ```ruby def frame end ```