### Install Development Tools (Ubuntu) Source: https://github.com/microsoft/playwright-java/blob/main/CONTRIBUTING.md Installs git, Java JDK, and Maven on Ubuntu 20.04. Ensure these are installed before proceeding. ```sh sudo apt-get install git openjdk-11-jdk maven unzip ``` -------------------------------- ### Compile and Run Playwright Java Example Source: https://github.com/microsoft/playwright-java/blob/main/examples/README.md Use this command to compile and execute a Playwright Java example using Maven. Ensure you have Maven installed and the project configured. ```sh mvn compile exec:java -Dexec.mainClass=org.example.PageScreenshot ``` -------------------------------- ### Initialize Playwright in Java Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/grid-iframe-in-shadow.html This snippet shows how to initialize Playwright and launch a browser instance. Ensure Playwright is installed and dependencies are met. ```java import com.microsoft.playwright.*; public class PlaywrightExample { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType chromium = playwright.chromium(); Browser browser = chromium.launch(); Page page = browser.newPage(); page.navigate("https://playwright.dev"); System.out.println(page.title()); browser.close(); } } } ``` -------------------------------- ### Keyboard Event Listener Setup Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/keyboard.html Attaches event listeners to a textarea to capture and log keyboard interaction details. Requires a DOM environment with a textarea element. ```javascript window.result = ""; let textarea = document.querySelector('textarea'); textarea.focus(); textarea.addEventListener('keydown', event => { log('Keydown:', event.key, event.code, event.which, modifiers(event)); }); textarea.addEventListener('keypress', event => { log('Keypress:', event.key, event.code, event.which, event.charCode, modifiers(event)); }); textarea.addEventListener('keyup', event => { log('Keyup:', event.key, event.code, event.which, modifiers(event)); }); function modifiers(event) { let m = [ ]; if (event.altKey) m.push('Alt') if (event.ctrlKey) m.push('Control'); if (event.shiftKey) m.push('Shift') return '[' + m.join(' ') + ']'; } function log(...args) { console.log.apply(console, args); result += args.join(' ') + '\n'; } function getResult() { let temp = result.trim(); result = ""; return temp; } ``` -------------------------------- ### Example Semantic Commit Message Source: https://github.com/microsoft/playwright-java/blob/main/CONTRIBUTING.md An example illustrating the Semantic Commit Messages format for a bug fix in Firefox. ```markdown fix(firefox): make sure session cookies work This patch fixes session cookies in firefox browser. Fixes #123, fixes #234 ``` -------------------------------- ### Start Continuous Jumping Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/animating-button.html Initializes the jumping sequence using both setInterval and requestAnimationFrame. ```javascript function startJumping() { x = 0; const moveIt = () => { jump(); requestAnimationFrame(moveIt); }; setInterval(jump, 0); moveIt(); } ``` -------------------------------- ### Initialize and Render WebGL Scene Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/screenshots/webgl.html Initializes the WebGL context, compiles the shader program, sets up vertex data, and draws a triangle strip. ```javascript var gl = document.getElementById("webgl") .getContext("experimental-webgl"); gl.clearColor(0.8, 0.8, 0.8, 1); gl.clear(gl.COLOR_BUFFER_BIT); var prog = shaderProgram(gl, "attribute vec3 pos;"+ "void main() {"+ " gl_Position = vec4(pos, 2.0);"+ "}", "void main() {"+ " gl_FragColor = vec4(0.5, 0.5, 1.0, 1.0);"+ "}" ); gl.useProgram(prog); attributeSetFloats(gl, prog, "pos", 3, [ -1, 0, 0, 0, 1, 0, 0, -1, 0, 1, 0, 0 ]); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); ``` -------------------------------- ### Build and Test with Maven Source: https://github.com/microsoft/playwright-java/blob/main/CONTRIBUTING.md Commands to compile and run tests using Maven. Includes options for executing single tests or test classes. ```bash mvn compile mvn test # Executing a single test BROWSER=chromium mvn test -Dtest=TestPageNetworkSizes#shouldHaveTheCorrectResponseBodySize # Executing a single test class BROWSER=chromium mvn test -Dtest=TestPageNetworkSizes ``` -------------------------------- ### Create and Use a Web Worker in Java Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/worker/worker.html Instantiate a new Web Worker and set up a message handler to log messages received from the worker. Ensure 'worker.js' is available in the correct path. ```java var worker = new Worker('worker.js'); worker.onmessage = function(message) { console.log(message.data); }; ``` -------------------------------- ### Basic HTML and JavaScript for Div Creation Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/overflow.html This snippet demonstrates basic HTML and JavaScript to create and style multiple div elements dynamically. It sets up CSS for the body and divs, then uses JavaScript to append 200 divs with alternating background colors. ```html body { margin: 0; padding: 0; } div { display: inline-flex; width: 50px; height: 50px; border-right: 1px solid black; border-bottom: 1px solid black; } ``` ```javascript const colors = ['#222', '#444', '#666', '#888', '#aaa' ]; for (let i = 0; i < 200; ++i) { const div = document.createElement('div'); div.style.setProperty('background-color', colors[i % 5]); document.body.appendChild(div); } ``` -------------------------------- ### Download and Assemble Playwright Driver Source: https://github.com/microsoft/playwright-java/blob/main/CONTRIBUTING.md Downloads and assembles the Playwright driver and Node.js binaries. This script is essential for setting up the driver components. ```bash scripts/download_driver.sh ``` -------------------------------- ### Load and Instantiate WebAssembly Table Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/wasm/table2.html Use this function to create a WebAssembly Table, fetch a WASM module, and instantiate it with the table. Ensure the WASM module is designed to interact with the provided table. ```javascript async function loadTable() { const tbl = new WebAssembly.Table({ initial: 2, element: 'anyfunc' }); const response = await fetch('table2.wasm'); const body = await response.arrayBuffer(); await WebAssembly.instantiate(body, { js: { tbl: tbl } }); return `${tbl.get(0)( )}, ${tbl.get(1)( )}`; } ``` -------------------------------- ### Basic Page Navigation in Java Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/grid-iframe-in-shadow.html Demonstrates navigating to a URL and retrieving the page title. This is a fundamental operation for web automation. ```java Page page = browser.newPage(); page.navigate("https://playwright.dev"); System.out.println(page.title()); ``` -------------------------------- ### Compile WebGL Shader Program Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/screenshots/webgl.html Creates and links a WebGL program from vertex and fragment shader source strings. Throws an error if compilation or linking fails. ```javascript function shaderProgram(gl, vs, fs) { var prog = gl.createProgram(); var addshader = function(type, source) { var s = gl.createShader((type == 'vertex') ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER); gl.shaderSource(s, source); gl.compileShader(s); if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) { throw "Could not compile "+type+ " shader:\n\n"+gl.getShaderInfoLog(s); } gl.attachShader(prog, s); }; addshader('vertex', vs); addshader('fragment', fs); gl.linkProgram(prog); if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) { throw "Could not link the shader program!"; } return prog; } ``` -------------------------------- ### Execute conditional logic and arrow functions Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/jscoverage/involved.html Demonstrates basic conditional statements, ternary operators, and arrow function definitions. ```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(); ``` -------------------------------- ### Download Blob Data in JavaScript Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/download-blob.html Use this function to initiate a file download from raw data. It creates a temporary DOM element to handle the download process. ```javascript const download = (data, filename) => { const a = document.createElement("a"); a.style = "display: none"; document.body.appendChild(a); a.style = "display: none"; const blob = new Blob([data], { type: "octet/stream" }); const url = window.URL.createObjectURL(blob); a.href = url; a.download = filename; a.click(); window.URL.revokeObjectURL(url); document.body.removeChild(a); }; const downloadIt = () => { download("Hello world", "example.txt"); } ``` -------------------------------- ### Generate test certificates Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/client-certificates/README.md Executes the generation script to create all necessary test certificates. ```bash bash generate.sh ``` -------------------------------- ### Generate Palette and Render DOM Elements Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/grid.html Creates a color palette and populates the document body with boxes containing digit images. Requires an existing directory structure for digit images. ```javascript document.addEventListener('DOMContentLoaded', function() { function generatePalette(amount) { var result = []; var hueStep = 360 / amount; for (var i = 0; i < amount; ++i) result.push('hsl(' + (hueStep * i) + ', 100%, 90%)'); return result; } var palette = generatePalette(100); for (var i = 0; i < 200; ++i) { var box = document.createElement('div'); box.classList.add('box'); box.style.setProperty('background-color', palette[i % palette.length]); var x = i; do { var digit = x % 10; x = (x / 10)|0; var img = document.createElement('img'); img.src = `./digits/${digit}.png`; box.insertBefore(img, box.firstChild); } while (x); document.body.appendChild(box); } }); ``` -------------------------------- ### Define CSS Transition Styles Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/css-transition.html Sets the initial state and transition properties for the target div element. ```css div { position: absolute; top: 0; left: 0; width: 200px; height: 100px; background-color: red; transition: all 10s; } .transition { transform: rotate(360deg); } ``` -------------------------------- ### Create and Animate Button Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/animating-button.html Creates a button element, applies a continuous animation, and sets a global flag on click. ```javascript function addButton() { const button = document.createElement('button'); button.textContent = 'Click me'; button.style.animation = '3s linear move'; button.style.animationIterationCount = 'infinite'; button.addEventListener('click', () => window.clicked = true); document.body.appendChild(button); } ``` -------------------------------- ### Simulate Touch Events in JavaScript Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/touches.html This JavaScript snippet sets up event listeners for touch events on a button and logs touch identifiers. It's useful for testing touch interactions in a browser environment. ```javascript window.result = []; const button = document.querySelector('button'); button.style.height = '200px'; button.style.width = '200px'; button.focus(); button.addEventListener('touchstart', event => { log('Touchstart:', ...Array.from(event.changedTouches).map(touch => touch.identifier)); }); button.addEventListener('touchend', event => { log('Touchend:', ...Array.from(event.changedTouches).map(touch => touch.identifier)); }); button.addEventListener('touchmove', event => { log('Touchmove:', ...Array.from(event.changedTouches).map(touch => touch.identifier)); }); function log(...args) { console.log.apply(console, args); result.push(args.join(' ')); } function getResult() { let temp = result; result = []; return temp; } ``` -------------------------------- ### Create and Append to Shadow DOM Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/shadow.html Use this code to attach a Shadow DOM to an element and populate it with content. Ensure the DOM is loaded before execution. ```javascript let h1 = null; window.button = null; let clicked = false; window.addEventListener('DOMContentLoaded', () => { const shadowRoot = document.body.attachShadow({mode: 'open'}); h1 = document.createElement('h1'); h1.textContent = 'Hellow Shadow DOM v1'; button = document.createElement('button'); button.textContent = 'Click'; button.addEventListener('click', () => clicked = true); shadowRoot.appendChild(h1); shadowRoot.appendChild(button); }); ``` -------------------------------- ### Roll the Playwright driver Source: https://github.com/microsoft/playwright-java/blob/main/ROLLING.md Execute the shell script to update the driver and regenerate sources. ```bash ./scripts/roll_driver.sh next ``` -------------------------------- ### Simulate and Capture Button Click Event Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/button.html This JavaScript code sets up an event listener on a button to capture click event details. It initializes result variables and updates them with event properties like offsetX, offsetY, pageX, pageY, shiftKey, bubbles, cancelable, and composed when the button is clicked. Use this to verify click interactions and event data. ```javascript window.result = 'Was not clicked'; window.offsetX = undefined; window.offsetY = undefined; window.pageX = undefined; window.pageY = undefined; window.shiftKey = undefined; window.pageX = undefined; window.pageY = undefined; window.bubbles = undefined; document.querySelector('button').addEventListener('click', e => { result = 'Clicked'; offsetX = e.offsetX; offsetY = e.offsetY; pageX = e.pageX; pageY = e.pageY; shiftKey = e.shiftKey; bubbles = e.bubbles; cancelable = e.cancelable; composed = e.composed; }, false); ``` -------------------------------- ### Perform Basic Canvas Drawing Operations Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/screenshots/canvas.html Initializes a 2D context on a canvas element and executes standard drawing commands. ```javascript const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); ctx.fillRect(25, 25, 100, 100); ctx.clearRect(45, 45, 60, 60); ctx.strokeRect(50, 50, 50, 50); ``` -------------------------------- ### Construct Nested Shadow DOM Structure Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/deep-shadow.html Creates a DOM tree with three nested shadow roots containing test elements. Use this to simulate complex component hierarchies. ```javascript window.addEventListener('DOMContentLoaded', () => { const outer = document.createElement('section'); document.body.appendChild(outer); const root1 = document.createElement('div'); root1.setAttribute('id', 'root1'); outer.appendChild(root1); const shadowRoot1 = root1.attachShadow({mode: 'open'}); const span1 = document.createElement('span'); span1.setAttribute('data-testid', 'foo'); span1.textContent = 'Hello from root1'; shadowRoot1.appendChild(span1); const root2 = document.createElement('div'); shadowRoot1.appendChild(root2); const shadowRoot2 = root2.attachShadow({mode: 'open'}); const span2 = document.createElement('span'); span2.setAttribute('data-testid', 'foo'); span2.setAttribute('id', 'target'); span2.textContent = 'Hello from root2'; shadowRoot2.appendChild(span2); const root3 = document.createElement('div'); shadowRoot1.appendChild(root3); const shadowRoot3 = root3.attachShadow({mode: 'open'}); const span3 = document.createElement('span'); span3.setAttribute('data-testid', 'foo'); span3.textContent = 'Hello from root3'; shadowRoot3.appendChild(span3); const span4 = document.createElement('span'); span4.textContent = 'Hello from root3 #2'; span4.setAttribute('attr', 'value space'); shadowRoot3.appendChild(span4); }); ``` -------------------------------- ### Generate scrollable test buttons Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/scrollable.html Creates 100 buttons in the DOM with click and context menu event listeners for testing interaction in scrollable containers. ```javascript for (let i = 0; i < 100; i++) { let button = document.createElement('button'); button.textContent = i + ': not clicked'; button.id = 'button-' + i; button.onclick = () => button.textContent = 'clicked'; button.oncontextmenu = event => { event.preventDefault(); button.textContent = 'context menu'; } document.body.appendChild(button); document.body.appendChild(document.createElement('br')); } ``` -------------------------------- ### Drag and Drop CSS and JavaScript Handlers Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/drag-n-drop.html Includes CSS for element styling and JavaScript functions for dragstart, dragover, and drop events. ```css div:not(.mouse-helper) { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } ``` ```javascript function dragstart_handler(ev) { ev.currentTarget.style.border = "dashed"; ev.dataTransfer.setData("text/plain", ev.target.id); } function dragover_handler(ev) { ev.preventDefault(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } ``` -------------------------------- ### Register and await service worker activation Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/serviceworkers/fetch/sw.html Use this snippet to initiate service worker registration and create a promise that resolves when the controller changes. ```javascript window.registrationPromise = navigator.serviceWorker.register('sw.js'); window.activationPromise = new Promise(resolve => navigator.serviceWorker.oncontrollerchange = resolve); ``` -------------------------------- ### Register Service Worker and Fetch Data Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/serviceworkers/fetchdummy/sw.html Initializes service worker registration and provides an asynchronous function to fetch text content from a given URL. ```javascript window.registrationPromise = navigator.serviceWorker.register('sw.js'); window.activationPromise = new Promise(resolve => navigator.serviceWorker.oncontrollerchange = resolve); async function fetchDummy(name) { const response = await fetch(name); if (!response.ok) return 'FAILURE: ' + response.statusText; const text = await response.text(); return text; } ``` -------------------------------- ### Handle beforeunload event Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/beforeunload.html Use this snippet to manage browser navigation warnings. It includes specific handling for Chromium/WebKit and Firefox. ```javascript window.addEventListener('beforeunload', event => { // Chromium & WebKit way. event.returnValue = 'Leave?'; // Firefox way. event.preventDefault(); }); ``` -------------------------------- ### Navigate and Screenshot Across Browsers in Java Source: https://github.com/microsoft/playwright-java/blob/main/README.md This snippet demonstrates how to navigate to a webpage and take a screenshot using Playwright in Chromium, Firefox, and WebKit. Ensure Playwright is set up in your project. ```java import com.microsoft.playwright.*; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; public class PageScreenshot { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { List browserTypes = Arrays.asList( playwright.chromium(), playwright.webkit(), playwright.firefox() ); for (BrowserType browserType : browserTypes) { try (Browser browser = browserType.launch()) { BrowserContext context = browser.newContext(); Page page = context.newPage(); page.navigate("https://playwright.dev/"); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot-" + browserType.name() + ".png"))); } } } } } ``` -------------------------------- ### Create and Append iframe and Button Elements Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/button-overlay-oopif.html This JavaScript code snippet demonstrates how to create an iframe and a button element, set their properties, and append them to the document's body. It's useful for setting up a test environment or simulating user interactions within a web page. ```javascript window.addEventListener('DOMContentLoaded', () => { const iframe = document.createElement('iframe'); const url = new URL(location.href); url.hostname = url.hostname === 'localhost' ? '127.0.0.1' : 'localhost'; url.pathname = '/grid.html'; iframe.src = url.toString(); document.body.append(iframe); const button = document.createElement('button'); button.textContent = 'CLICK ME'; button.addEventListener('click', () => { window.BUTTON_CLICKED = true; }, false); document.body.append(button); }, false); ``` -------------------------------- ### Create and Commit Branch with Semantic Message Source: https://github.com/microsoft/playwright-java/blob/main/CLAUDE.md Use this command to create a new branch for an issue fix and commit changes with a semantic message, including a reference to the issue. ```bash git checkout -b fix-39562 # ... make changes ... git add git commit -m "$(cat <<'EOF' fix(proxy): handle SOCKS proxy authentication Fixes: https://github.com/microsoft/playwright-java/issues/39562 EOF )" ``` -------------------------------- ### Generate Java API Source: https://github.com/microsoft/playwright-java/blob/main/CONTRIBUTING.md Generates the public Java API from api.json. This script fetches upstream Playwright source if PW_SRC_DIR is not set. ```bash ./scripts/generate_api.sh ``` -------------------------------- ### Convert PEM files to PKCS12 Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/client-certificates/README.md Converts PEM certificates to PKCS12 format required by Java servers. ```bash bash generate_java.sh ``` -------------------------------- ### Clone Playwright Java Repository Source: https://github.com/microsoft/playwright-java/blob/main/CONTRIBUTING.md Clones the Playwright Java repository and navigates into the project directory. This is the first step in obtaining the code. ```bash git clone https://github.com/microsoft/playwright-java cd playwright-java ``` -------------------------------- ### Define CSS Styles and Animations Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/animating-button.html Sets the base margin and padding for the document and defines a keyframe animation for horizontal movement. ```css body, html { margin: 0; padding: 0; } @keyframes move { from { marign-left: 0; } to { margin-left: 100px; } } ``` -------------------------------- ### Create GitHub Pull Request Source: https://github.com/microsoft/playwright-java/blob/main/CLAUDE.md This command uses the GitHub CLI to create a pull request for a feature branch, including a title and a brief body summarizing the changes. ```bash gh pr create --repo microsoft/playwright-java --head :fix-39562 \ --title "fix(proxy): handle SOCKS proxy authentication" \ --body "$(cat <<'EOF' ## Summary - Fixes https://github.com/microsoft/playwright-java/issues/39562 EOF )" ``` -------------------------------- ### CSS for Interstitial and Target Elements Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/handle-locator.html Styles for positioning, visibility, and interaction states of the target element and the interstitial overlay. Use this CSS to set up the visual behavior of the test page. ```css Interstitial test body { position: relative; } #target.removed { display: none; } #target.hidden { visibility: hidden; } #target:hover { background: yellow; } #interstitial { position: absolute; top: 0; left: 0; width: 300px; height: 300px; border: 1px solid black; background: rgba(255, 180, 180); display: none; } #interstitial.visible { display: block; } #close { margin: 50px; } ``` -------------------------------- ### Inject CSS and DOM elements Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/overflow-large.html Applies styles to the body and creates a grid of colored divs via script injection. ```css body { margin: 0; padding: 0; } div { display: inline-flex; width: 50px; height: 50px; border-right: 1px solid black; border-bottom: 1px solid black; } ``` ```javascript const colors = ['#222', '#444', '#666', '#888', '#aaa']; for (let i = 0; i < 1000; ++i) { const div = document.createElement('div'); div.style.setProperty('background-color', colors[i % 5]); document.body.appendChild(div); } ``` -------------------------------- ### JavaScript for Interstitial Interaction Logic Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/handle-locator.html Handles user clicks on the target and close buttons, managing the visibility of the interstitial overlay. Includes logic for delayed closing via timeouts. ```javascript const target = document.querySelector('#target'); const interstitial = document.querySelector('#interstitial'); const close = document.querySelector('#close'); target.addEventListener('click', () => { window.clicked = (window.clicked ?? 0) + 1; }, false); close.addEventListener('click', () => { const closeInterstitial = () => { interstitial.classList.remove('visible'); target.classList.remove('hidden'); target.classList.remove('removed'); }; if (interstitial.classList.contains('timeout')) setTimeout(closeInterstitial, 3000); else closeInterstitial(); }); ``` ```javascript let timesToShow = 0; function setupAnnoyingInterstitial(event, times, capture) { timesToShow = times; const listener = () => { timesToShow--; interstitial.classList.add('visible'); interstitial.getBoundingClientRect(); if (!timesToShow && event !== 'none') target.removeEventListener(event, listener, capture === 'capture'); }; if (event === 'hide' || event === 'timeout') { target.classList.add('hidden'); listener(); if (event === 'timeout') interstitial.classList.add('timeout'); } else if (event === 'remove') { target.classList.add('removed'); listener(); } else if (event === 'none') { listener(); } else { target.addEventListener(event, listener, capture === 'capture'); } } ``` -------------------------------- ### Video Playback and Frame Control Utilities Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/player.html Asynchronous functions to manipulate HTML5 video elements. Requires an active video element in the DOM. ```javascript async function playToTheEnd() { const video = document.querySelector('video'); const result = new Promise(r => video.onended = r); video.play(); return await result; } async function playOneFrame() { const video = document.querySelector('video'); const result = new Promise(r => video.onpause = r); video.ontimeupdate = () => { video.pause(); video.ontimeupdate = null; }; video.play(); return await result; } async function playNFrames(n) { for (let i = 0; i < n; i++) await playOneFrame(); } let _frameCount = -1; async function countFrames() { if (_frameCount === -1) { const video = document.querySelector('video'); if (!video.duration) return 0; if (video.currentTime) await playToTheEnd(); let count = 0; while (true) { ++count; await playOneFrame(); if (video.ended) break; } _frameCount = count; } return _frameCount; } async function seekLastFrame() { let frameCount = await countFrames(); await playNFrames(frameCount); return frameCount; } ``` -------------------------------- ### Create a rotating square animation with CSS Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/rotate-z.html Defines a square element with an infinite rotation animation using keyframes. ```css .square { position: absolute; top: 0; left: 0; width: 200px; height: 100px; background-color: red; animation-name: z-spin; animation-duration: 5s; animation-iteration-count: infinite; animation-timing-function: linear; } @keyframes z-spin { 0% { transform: rotateZ(0deg); } 100% { transform: rotateZ(360deg); } } ``` -------------------------------- ### Initialize and Load Iframe on DOM Load Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/dynamic-oopif.html This JavaScript code initializes an iframe and loads remote content into it when the DOM is fully loaded. It appends the iframe to the document body. ```javascript window.addEventListener('DOMContentLoaded', () => { const iframe = document.createElement('iframe'); goRemote(iframe); document.body.appendChild(iframe); }, false); ``` -------------------------------- ### Define Box and Animation Styles Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/grid.html CSS rules for layout, box sizing, and keyframe animations. Hides the browser scrollbar by default. ```css body { margin: 0; padding: 0; } .box { font-family: arial; display: inline-flex; align-items: center; justify-content: center; margin: 0; padding: 0; width: 50px; height: 50px; box-sizing: border-box; border: 1px solid darkgray; } ::-webkit-scrollbar { display: none; } @keyframes move { from { left: -500px; background-color: cyan; } to { left: 0; background-color: rgb(255, 210, 204); } } .box.animation { position: relative; animation: 2s linear 0s move forwards; } ``` -------------------------------- ### Handle Select Element Events in JavaScript Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/select.html This JavaScript code sets up event listeners for 'input', 'change', 'bubblinginput', and 'bubblingchange' events on a select element. It captures the values of selected options and stores them in a global 'result' object. This is useful for tracking user interactions with select elements. ```javascript window.result = { onInput: null, onChange: null, onBubblingChange: null, onBubblingInput: null, }; let select = document.querySelector('select'); function makeEmpty() { for (let i = select.options.length - 1; i >= 0; --i) { select.remove(i); } } function makeMultiple() { select.setAttribute('multiple', true); } select.addEventListener('input', () => { result.onInput = Array.from(select.querySelectorAll('option:checked')).map((option) => { return option.value; }); }, false); select.addEventListener('change', () => { result.onChange = Array.from(select.querySelectorAll('option:checked')).map((option) => { return option.value; }); }, false); document.body.addEventListener('input', () => { result.onBubblingInput = Array.from(select.querySelectorAll('option:checked')).map((option) => { return option.value; }); }, false); document.body.addEventListener('change', () => { result.onBubblingChange = Array.from(select.querySelectorAll('option:checked')).map((option) => { return option.value; }); }, false); ``` -------------------------------- ### Update Driver Version Source: https://github.com/microsoft/playwright-java/blob/main/CONTRIBUTING.md Updates the driver to a specific version using a provided script. The version can be found in the publish canary and release action logs. ```bash scripts/roll_driver.sh [version] ``` -------------------------------- ### Define CSS styles for a div element Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/web-animation.html Sets the positioning, dimensions, and background color for a div element. ```css div { position: absolute; top: 0; left: 0; width: 200px; height: 100px; background-color: red; } ``` -------------------------------- ### Execute JavaScript for LocalStorage Manipulation Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/redirectloop1.html This snippet modifies window.localStorage and triggers a page navigation. It is intended for use within browser contexts to simulate state changes or navigation loops. ```javascript setTimeout(() => { const iter = window.localStorage.iter || ''; window.localStorage.iter = iter + 'a'; if (iter.length === 10) return; window.location.href = window.location.href.replace('loop1', 'loop2'); }, 1); ``` -------------------------------- ### Handle Click Events in JavaScript Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/wrappedlink.html This JavaScript snippet demonstrates how to add an event listener to an anchor tag to detect clicks and set a global variable. It's useful for tracking user interactions on a webpage. ```javascript document.querySelector('a').addEventListener('click', () => { window.__clicked = true; }); ``` -------------------------------- ### Inject Shadow DOM with CSS Animation Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/rotate-z-shadow-dom.html Attaches an open shadow root to the document body and appends a styled div with a continuous rotation animation. ```javascript window.addEventListener('DOMContentLoaded', () => { const shadow = document.body.attachShadow({mode: 'open'}); shadow.append(document.createElement('div')); const style = document.createElement('style'); style.textContent = ` div { position: absolute; top: 0; left: 0; width: 200px; height: 100px; background-color: red; animation-name: z-spin; animation-duration: 5s; animation-iteration-count: infinite; animation-timing-function: linear; } @keyframes z-spin { 0% { transform: rotateZ(0deg); } 100% { transform: rotateZ(360deg); } } `; shadow.append(style); }, false); ``` -------------------------------- ### JavaScript for Button Click Events Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/offscreenbuttons.html This JavaScript code sets up event listeners for buttons. When a button is clicked, it logs a message to the console indicating which button was pressed. ```javascript window.addEventListener('DOMContentLoaded', () => { for (const button of Array.from(document.querySelectorAll('button'))) button.addEventListener('click', () => console.log('button #' + button.textContent + ' clicked'), false); }, false); ``` -------------------------------- ### Trigger Transition via JavaScript Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/css-transition.html Adds the transition class to the div element once the window has finished loading. ```javascript window.addEventListener('load', () => { document.querySelector('div').classList.add('transition'); }, false); ``` -------------------------------- ### Semantic Commit Message Format Source: https://github.com/microsoft/playwright-java/blob/main/CONTRIBUTING.md Defines the structure for commit messages, including label, namespace, title, description, and footer. Follows the Semantic Commit Messages format. ```markdown label(namespace): title description footer ``` -------------------------------- ### CSS for Button and Layout Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/offscreenbuttons.html This CSS defines the styling and positioning for buttons and the overall page layout. It's used to create a specific visual arrangement for interactive elements. ```css button { position: absolute; width: 100px; height: 20px; margin: 0; } body, html { margin: 0; padding: 0; height: 100%; width: 100%; position: relative; } div { position: absolute; left: 0; top: 0; right: 0; bottom: 0; } #btn0 { right: 0px; top: 0; } #btn1 { right: -10px; top: 25px; } #btn2 { right: -20px; top: 50px; } #btn3 { right: -30px; top: 75px; } #btn4 { right: -40px; top: 100px; } #btn5 { right: -50px; top: 125px; } #btn6 { right: -60px; top: 150px; } #btn7 { right: -70px; top: 175px; } #btn8 { right: -80px; top: 200px; } #btn9 { right: -90px; top: 225px; } #btn10 { right: -100px; top: 250px; } ``` -------------------------------- ### Capture input events for textarea and input elements Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/textarea.html Attaches event listeners to textarea and input elements to update a global result variable on input. ```javascript window.result = ''; let textarea = document.querySelector('textarea'); textarea.addEventListener('input', () => result = textarea.value, false); let input = document.querySelector('input'); input.addEventListener('input', () => result = input.value, false); ``` -------------------------------- ### Track Checkbox Events and State Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/checkbox.html Captures checkbox interaction events and the resulting checked state in a global result object. Useful for verifying input behavior during automated testing. ```javascript window.result = { check: null, events: [], }; let checkbox = document.querySelector('input'); const events = [ 'change', 'click', 'dblclick', 'input', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', 'mouseup', ]; for (let event of events) { checkbox.addEventListener(event, () => { if (['change', 'click', 'dblclick', 'input'].includes(event) === true) { result.check = checkbox.checked; } result.events.push(event); }, false); } ``` -------------------------------- ### Create a Custom React Button Component Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/react.html Defines a reusable React button component with hover effects and click handlers. This component can be integrated into React applications for interactive elements. ```javascript window.e = React.createElement; window.reactRoot = document.querySelector('.react-root'); window.renderComponent = c => ReactDOM.render(c, window.reactRoot); window.MyButton = class MyButton extends React.Component { constructor(props) { super(props); this.state = { hovered: false }; } render() { return e('button', { disabled: !!this.props.disabled, onClick: () => { window[this.props.name] = true; }, onMouseEnter: () => { if (this.props.renameOnHover) this.setState({ hovered: true }); if (this.props.onHover) this.props.onHover(); }, }, this.state.hovered ? 'Hovered' : this.props.name); } }; ``` -------------------------------- ### Attach Frame to DOM Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/frames/nested-frames.html Appends an iframe element to the document body and returns a string upon successful load. Requires a frame ID and URL. ```javascript async function attachFrame(frameId, url) { var frame = document.createElement('iframe'); frame.src = url; frame.id = frameId; document.body.appendChild(frame); await new Promise(x => frame.onload = x); return 'kazakh'; } ``` -------------------------------- ### Jump Button Position Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/animating-button.html Updates the button's left margin to simulate a jumping effect. ```javascript let x = 0; function jump() { x += 300; const button = document.querySelector('button'); button.style.marginLeft = x + 'px'; } ``` -------------------------------- ### Change Background Color with JavaScript Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/background-color.html This JavaScript function changes the background color of the document body based on the URL hash. Ensure the script is loaded and executed in the browser context. ```javascript function changeBackground() { const color = location.hash.substr(1); document.body.style.backgroundColor = color; } ``` -------------------------------- ### CSS Grid Layout Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/checkerboard.html This CSS defines a grid layout for a container with two columns and styles for cells, including specific colors for grey and red cells. This is a basic CSS structure. ```css body { margin: 0; } .container { display: grid; background-color: rgb(0, 0, 0); grid-template-columns: auto auto; width: 100%; height: 100%; } .cell { border: none; font-size: 30px; text-align: center; } .cell.grey { background-color: rgb(100, 100, 100); } .cell.red { background-color: rgb(255, 0, 0); } ``` -------------------------------- ### Test Rotated Button Click in Playwright Java Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/rotatedButton.html This snippet shows how to locate and click a button that has a CSS transform applied. Ensure the element is visible and actionable before attempting to click. ```java import static org.junit.jupiter.api.Assertions.assertEquals; import com.microsoft.playwright.Page; import org.junit.jupiter.api.Test; public class RotatedButtonTest { @Test void rotatedButtonTest() { // Navigate to the page with the rotated button page.navigate("data:text/html,"); // Click the button page.locator("button").click(); // Assert that the button was clicked assertEquals("Clicked", page.evaluate("() => window.result")); } } ``` -------------------------------- ### Format Number with Locale and Remove Spaces Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/formatted-number.html Formats a number to a locale-specific string and removes whitespace. Useful for consistent number representation across different environments. ```javascript window.result = (1000000.50).toLocaleString().replace(/\s/g, ' '); window.initialNavigatorLanguage = navigator.language; ``` -------------------------------- ### Animate a div element using Web Animations API Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/web-animation.html Applies a rotation animation to the first div element found in the document. ```javascript document.querySelector('div').animate( [ { transform: 'rotate(0deg)' }, { transform: 'rotate(360deg)' } ], { duration: 3000, iterations: Infinity } ); ``` -------------------------------- ### Load Local Iframe Content Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/dynamic-oopif.html This JavaScript function reloads the iframe to display local content, typically used for debugging or local development. ```javascript function goLocal() { document.querySelector('iframe').src = location.href.replace('dynamic-oopif.html', 'grid.html'); } ``` -------------------------------- ### Capture Geolocation via Promise Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/geolocation.html Use this snippet to asynchronously retrieve the current geographic coordinates from the browser's geolocation API. ```javascript window.geolocationPromise = new Promise(resolve => { navigator.geolocation.getCurrentPosition(position => { resolve({latitude: position.coords.latitude, longitude: position.coords.longitude}); }); }); ``` -------------------------------- ### Simulate JavaScript Error Propagation Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/error.html This snippet defines a chain of function calls that eventually throws an error, useful for testing error handling and stack trace reporting in Playwright. ```javascript console.error('Not a JS error'); a(); function a() { b(); } function b() { c(); } function c() { window.e = new Error('Fancy error!'); throw window.e; } //# sourceURL=myscript.js ``` -------------------------------- ### Load Remote Iframe Content Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/dynamic-oopif.html This JavaScript function loads remote content into an iframe, dynamically adjusting the hostname between localhost and 127.0.0.1. It's useful for testing cross-origin scenarios or different network configurations. ```javascript function goRemote(iframe) { iframe = iframe || document.querySelector('iframe'); const url = new URL(location.href); url.hostname = url.hostname === 'localhost' ? '127.0.0.1' : 'localhost'; url.pathname = '/grid.html'; iframe.src = url.toString(); } ``` -------------------------------- ### Set Vertex Attribute Floats Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/screenshots/webgl.html Binds a float array to a specified vertex attribute location in the current WebGL program. ```javascript function attributeSetFloats(gl, prog, attr_name, rsize, arr) { gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(arr), gl.STATIC_DRAW); var attr = gl.getAttribLocation(prog, attr_name); gl.enableVertexAttribArray(attr); gl.vertexAttribPointer(attr, rsize, gl.FLOAT, false, 0, 0); } ``` -------------------------------- ### Manipulate DOM with JavaScript in Playwright Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/snapshot/snapshot-with-css.html This snippet demonstrates how to interact with the DOM using JavaScript within Playwright. It modifies a textarea's value and dynamically adds elements and styles to a shadow DOM. ```javascript let shadow; window.addEventListener('DOMContentLoaded', () => { document.querySelector('textarea').value = 'After edit'; const root = document.querySelector('.root'); shadow = root.attachShadow({ mode: 'open' }); const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = './one.css'; shadow.appendChild(link); const imaged = document.createElement('div'); imaged.className = 'imaged'; shadow.appendChild(imaged); const iframe = document.createElement('iframe'); iframe.width = '600px'; iframe.height = '600px'; iframe.src = '../frames/nested-frames.html'; shadow.appendChild(iframe); }); window.addEventListener('load', () => { for (const rule of shadow.styleSheets[0].cssRules) { if (rule.styleSheet) { for (const rule2 of rule.styleSheet.cssRules) { if (rule2.cssText.includes('width: 200px')) rule2.style.width = '400px'; } } } }); ``` -------------------------------- ### Stop Button Animation Source: https://github.com/microsoft/playwright-java/blob/main/playwright/src/test/resources/input/animating-button.html Freezes the button at its current position and optionally removes it from the DOM. ```javascript function stopButton(remove) { const button = document.querySelector('button'); button.style.marginLeft = button.getBoundingClientRect().left + 'px'; button.style.animation = ''; if (remove) button.remove(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.