### Install Dependencies and Setup Project Source: https://github.com/microsoft/playwright-python/blob/main/ROLLING.md Installs dependencies, sets up pre-commit hooks, and installs the project in editable mode. ```bash python -m pip install --upgrade pip pip install -r local-requirements.txt pre-commit install pip install -e . ``` -------------------------------- ### Setup Playwright Python Environment Source: https://github.com/microsoft/playwright-python/blob/main/CLAUDE.md Installs Playwright Python, upgrades pip, installs local requirements, and sets up the project for local development. It also builds the Playwright driver from source. ```shell python3 -m venv env && source env/bin/activate pip install --upgrade pip pip install -r local-requirements.txt pip install -e . python -m build --wheel # clones microsoft/playwright @ DRIVER_SHA and builds the driver from source pre-commit install ``` -------------------------------- ### Install Dependencies Source: https://github.com/microsoft/playwright-python/blob/main/CONTRIBUTING.md Upgrades pip and installs project dependencies from local-requirements.txt. ```sh python -m pip install --upgrade pip pip install -r local-requirements.txt ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/microsoft/playwright-python/blob/main/CLAUDE.md Installs specific Playwright browser binaries. Avoid using the `--with-deps` flag as it may require sudo privileges. ```shell playwright install chromium ``` -------------------------------- ### Build and Install Playwright Python Source: https://github.com/microsoft/playwright-python/blob/main/CONTRIBUTING.md Installs the Playwright Python package in editable mode and builds a wheel from upstream sources. ```sh pip install -e . python -m build --wheel ``` -------------------------------- ### Format Code with Pre-commit Source: https://github.com/microsoft/playwright-python/blob/main/CONTRIBUTING.md Installs pre-commit hooks and formats all files in the repository. ```sh pre-commit install pre-commit run --all-files ``` -------------------------------- ### Create Scrollable Buttons Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/scrollable.html Generates 100 buttons with click and context menu handlers to simulate a scrollable list. This setup is useful for testing scrolling behavior and element interaction within a dynamic list. ```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')); } ``` -------------------------------- ### Start Continuous Button Jumping Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/animating-button.html Initiates a continuous jumping animation for the button using requestAnimationFrame and setInterval. ```javascript function startJumping() { x = 0; const moveIt = () => { jump(); requestAnimationFrame(moveIt); }; setInterval(jump, 0); moveIt(); } ``` -------------------------------- ### Setup Annoying Interstitial Logic Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/handle-locator.html This JavaScript function sets up logic for an interstitial element. It can be triggered by various events and control the visibility and behavior of both the interstitial and a target element. ```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(); }); 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'); } } ``` -------------------------------- ### Run Playwright Tests Source: https://github.com/microsoft/playwright-python/blob/main/CLAUDE.md Executes the Playwright test suite using pytest. Allows filtering tests by browser and name. Browsers are installed separately. ```shell pytest --browser chromium [-k name] ``` -------------------------------- ### Drag and Drop Event Handlers (JavaScript) Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/drag-n-drop.html These JavaScript functions handle the drag and drop events. `dragstart_handler` sets data and visual feedback when dragging starts. `dragover_handler` prevents the default behavior to allow dropping. `drop_handler` processes the dropped data and appends the element to the target. ```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)); } ``` -------------------------------- ### Get Current Geolocation Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/geolocation.html This snippet shows how to get the user's current position using the Geolocation API and resolve a Promise with the latitude and longitude. It requires user permission to access location. ```javascript window.geolocationPromise = new Promise(resolve => { navigator.geolocation.getCurrentPosition(position => { resolve({latitude: position.coords.latitude, longitude: position.coords.longitude}); }); }); ``` -------------------------------- ### Capture Textarea Input Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/textarea.html Captures the value of a textarea element when the input event fires. Use this to get real-time updates of user input in a textarea. ```javascript window.result = ''; let textarea = document.querySelector('textarea'); textarea.addEventListener('input', () => result = textarea.value, false); ``` -------------------------------- ### Configure Python Environment Source: https://github.com/microsoft/playwright-python/blob/main/CONTRIBUTING.md Sets up a Python 3.10 virtual environment and activates it. ```sh # You may need to install python 3.10 venv if it's missing, on Ubuntu just run `sudo apt-get install python3.10-venv` python3.10 -m venv env source ./env/bin/activate ``` -------------------------------- ### Simulating Touch Events Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/touches.html This snippet demonstrates how to set up event listeners for touch events (touchstart, touchend, touchmove) on a button element and log touch identifiers. It also includes functions to log messages and retrieve results. ```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; } ``` -------------------------------- ### Initialize and Communicate with a Web Worker Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/worker/worker.html This snippet shows how to create a new Web Worker instance and set up an event listener to receive messages from it. It's useful for offloading tasks to a background thread. ```javascript var worker = new Worker('worker.js'); worker.onmessage = function(message) { console.log(message.data); }; ``` -------------------------------- ### Create and Style Button Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/animating-button.html Creates a button element, sets its text, applies an animation, and adds a click listener. ```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); } ``` -------------------------------- ### Lint All Files with Pre-commit Source: https://github.com/microsoft/playwright-python/blob/main/CLAUDE.md Runs all configured pre-commit hooks across all files in the repository to ensure code quality and consistency. ```shell pre-commit run --all-files ``` -------------------------------- ### Regenerate Client Certificates Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/client-certificates/README.md Run this script to regenerate all client certificates. Ensure you have the necessary permissions and environment set up before execution. ```bash bash generate.sh ``` -------------------------------- ### Trigger Blob Download Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/download-blob.html This JavaScript function calls the `download` function with sample data and a filename to initiate the blob download process. ```javascript const downloadIt = () => { download("Hello world", "example.txt"); } ``` -------------------------------- ### Generate API JSON and Update API Source: https://github.com/microsoft/playwright-python/blob/main/ROLLING.md Generates the API JSON file and updates the API documentation. Ensure you are in the 'playwright' directory. ```bash API_JSON_MODE=1 node utils/doclint/generateApiJson.js > ../playwright-python/playwright/driver/package/api.json ./scripts/update_api.sh ``` -------------------------------- ### Asynchronous Browser Automation with Playwright Source: https://github.com/microsoft/playwright-python/blob/main/README.md Launches Chromium, Firefox, and WebKit browsers asynchronously, navigates to Playwright's website, takes a screenshot, and closes the browser. Ideal for I/O-bound operations where non-blocking execution is beneficial. ```python import asyncio from playwright.async_api import async_playwright async def main(): async with async_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: browser = await browser_type.launch() page = await browser.new_page() await page.goto('http://playwright.dev') await page.screenshot(path=f'example-{browser_type.name}.png') await browser.close() asyncio.run(main()) ``` -------------------------------- ### Synchronous Browser Automation with Playwright Source: https://github.com/microsoft/playwright-python/blob/main/README.md Launches Chromium, Firefox, and WebKit browsers, navigates to Playwright's website, takes a screenshot, and closes the browser. Use this for straightforward, sequential browser automation tasks. ```python from playwright.sync_api import sync_playwright with sync_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: browser = browser_type.launch() page = browser.new_page() page.goto('http://playwright.dev') page.screenshot(path=f'example-{browser_type.name}.png') browser.close() ``` -------------------------------- ### Collect Coverage Report Source: https://github.com/microsoft/playwright-python/blob/main/CONTRIBUTING.md Runs tests with coverage enabled and opens the generated HTML report. ```sh pytest --browser chromium --cov-report html --cov=playwright open htmlcov/index.html ``` -------------------------------- ### Simulate Button Click and Capture Event Properties Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/button.html This snippet demonstrates how to click a button and capture various properties of the click event, such as offset, page coordinates, and event bubbling behavior. Ensure the button element exists in the DOM before executing. ```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); ``` -------------------------------- ### Regenerate APIs Source: https://github.com/microsoft/playwright-python/blob/main/CONTRIBUTING.md Updates API definitions using a script and then formats the code. ```bash ./scripts/update_api.sh pre-commit run --all-files ``` -------------------------------- ### Download Blob Function Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/download-blob.html This JavaScript function handles the creation of a blob, generates a download URL, and simulates a click event to download the file. It cleans up by revoking the object URL and removing the anchor element. ```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); }; ``` -------------------------------- ### Run Playwright Tests Source: https://github.com/microsoft/playwright-python/blob/main/CONTRIBUTING.md Executes Playwright tests using the Chromium browser. ```sh pytest --browser chromium ``` -------------------------------- ### Select Element Event Listeners Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/select.html Sets up event listeners for input, change, and bubbling events on a select element and its parent body. Captures selected option values. ```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); ``` -------------------------------- ### Create Pull Request Source: https://github.com/microsoft/playwright-python/blob/main/CLAUDE.md Command to create a pull request on GitHub for the Playwright Python repository, including a title and body referencing the issue. ```bash git push origin fix-12345 gh pr create --repo microsoft/playwright-python --head username:fix-12345 \ --title "fix(asyncio): do not deadlock in atexit handler" \ --body "$(cat <<'EOF' ## Summary - Fixes https://github.com/microsoft/playwright-python/issues/12345 EOF )" ``` -------------------------------- ### Generate Dynamic Grid with Color Palette Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/grid.html This JavaScript code generates a grid of 200 `div` elements, each with a unique background color from a generated HSL palette. It also dynamically inserts images of digits into each element. ```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); } }); ``` -------------------------------- ### HTML Structure for Offscreen Buttons Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/offscreenbuttons.html Defines the CSS and HTML for positioning multiple buttons offscreen. Each button is absolutely positioned with increasing offsets. ```html 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; } ``` -------------------------------- ### Register Service Worker and Fetch Dummy Content Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/serviceworkers/fetchdummy/sw.html Registers the service worker and defines a function to fetch content, returning dummy responses or error messages. ```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-python/blob/main/tests/assets/beforeunload.html Attaches an event listener to the 'beforeunload' event. This is useful for prompting the user before they leave the page. It includes methods for both Chromium/WebKit and Firefox. ```javascript window.addEventListener('beforeunload', event => { // Chromium & WebKit way. event.returnValue = 'Leave?'; // Firefox way. event.preventDefault(); }); ``` -------------------------------- ### Attach and Load Nested Frame Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/frames/nested-frames.html This JavaScript function creates an iframe, sets its source and ID, appends it to the document body, and waits for the iframe to load. It returns a string upon successful loading. ```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'; } ``` -------------------------------- ### Create a New Git Branch for a Fix Source: https://github.com/microsoft/playwright-python/blob/main/CLAUDE.md Creates a new Git branch with a descriptive name, following the 'fix-issue-number' convention for bug fixes. ```shell git checkout -b fix-12345 ``` -------------------------------- ### CSS for Drag and Drop Elements Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/drag-n-drop.html Basic CSS styling for the draggable element and the drop zone. The `.mouse-helper` class is excluded from margin adjustments. ```css div:not(.mouse-helper) { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } ``` -------------------------------- ### Create and Append Shadow DOM Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/shadow.html Attaches a Shadow DOM to the document body and appends a heading and a button to it. This is useful for encapsulating UI components. ```javascript let h1 = null; let 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); }); ``` -------------------------------- ### Logging Keyboard Events in a Textarea Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/keyboard.html This snippet logs keydown, keypress, and keyup events from a textarea element. It captures event details such as key, code, which, and modifier keys. Ensure a textarea element exists in the DOM. ```javascript 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; } ``` -------------------------------- ### Listen for Click Events on an Anchor Tag Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/wrappedlink.html This snippet demonstrates how to attach an event listener to an anchor tag to detect click events. It sets a global variable when the click occurs. ```javascript document.querySelector('a').addEventListener('click', () => { window.__clicked = true; }); ``` -------------------------------- ### Basic CSS for Grid Elements Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/grid.html These CSS rules define the basic styling for the grid elements, including margin, padding, display properties, and scrollbar behavior. ```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; } ``` -------------------------------- ### Handle Checkbox Events Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/checkbox.html Attaches event listeners to a checkbox to track user interactions and state changes. Useful for validating checkbox behavior and capturing user input events. ```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); } ``` -------------------------------- ### Regenerate Playwright API Files Source: https://github.com/microsoft/playwright-python/blob/main/CLAUDE.md Updates the generated Python API files based on the Playwright driver's API.json. This script also runs pre-commit hooks on the generated files. ```shell ./scripts/update_api.sh ``` -------------------------------- ### Commit Message with Issue Fix Source: https://github.com/microsoft/playwright-python/blob/main/CLAUDE.md Use this format for commit messages when fixing an issue, referencing the issue number. ```bash git add git commit -m "$(cat <<'EOF' fix(asyncio): do not deadlock in atexit handler Fixes: https://github.com/microsoft/playwright-python/issues/12345 EOF )" ``` -------------------------------- ### Define CSS Animation Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/animating-button.html Defines a keyframe animation named 'move' that shifts an element's left margin. ```css body, html { margin: 0; padding: 0; } @keyframes move { from { marign-left: 0; } to { margin-left: 100px; } } ``` -------------------------------- ### Register Service Worker Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/serviceworkers/fetch/sw.html Registers the service worker script. This is typically done once when the application loads. ```javascript window.registrationPromise = navigator.serviceWorker.register('sw.js'); window.activationPromise = new Promise(resolve => navigator.serviceWorker.oncontrollerchange = resolve); ``` -------------------------------- ### JavaScript Event Listener for Button Clicks Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/offscreenbuttons.html Adds click event listeners to all button elements on the page. Logs the button number to the console when clicked. ```javascript window.addEventListener('DOMContentLoaded', () => { for (const button of Array.from(document.querySelectorAll('button'))) button.addEventListener('click', () => console.log('button #' + button.textContent + ' clicked'), false); }, false); ``` -------------------------------- ### Move Button Incrementally Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/animating-button.html Updates the button's left margin by a fixed increment. ```javascript let x = 0; function jump() { x += 300; const button = document.querySelector('button'); button.style.marginLeft = x + 'px'; } ``` -------------------------------- ### Check Typing Errors Source: https://github.com/microsoft/playwright-python/blob/main/CONTRIBUTING.md Uses mypy to check for typing errors in the Playwright Python code. ```sh mypy playwright ``` -------------------------------- ### React Component Definition Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/react.html Defines a custom React button component with hover effects and click handlers. The component manages its own 'hovered' state and can trigger external actions via props. ```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); } }; ``` -------------------------------- ### Capture Input Element Value Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/textarea.html Captures the value of a standard input element when the input event fires. This is useful for tracking user input in text fields. ```javascript let input = document.querySelector('input'); input.addEventListener('input', () => result = input.value, false); ``` -------------------------------- ### Handling JavaScript Errors Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/error.html This snippet demonstrates a scenario where a JavaScript error is thrown. Playwright captures and reports these errors. ```javascript console.error('Not a JS error'); a(); function a() { b(); } function b() { c(); } function c() { throw new Error('Fancy error!'); } //# sourceURL=myscript.js ``` -------------------------------- ### Stop Button Animation Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/animating-button.html Stops the button's animation and optionally removes the button element. It captures the current left margin before stopping. ```javascript function stopButton(remove) { const button = document.querySelector('button'); button.style.marginLeft = button.getBoundingClientRect().left + 'px'; button.style.animation = ''; if (remove) button.remove(); } ``` -------------------------------- ### Rotated Button HTML Structure Source: https://github.com/microsoft/playwright-python/blob/main/tests/assets/input/rotatedButton.html This HTML snippet defines a button with a CSS transform applied, simulating a rotated element. It includes a JavaScript function to update a result variable when the button is clicked. ```html Rotated button test Click target button { transform: rotateY(180deg); } window.result = 'Was not clicked'; function clicked() { result = 'Clicked'; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.