### 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: `