0

I want a playwright python mouse UI enable script. so can i can see my mouse to be working in visual for my humanize automation. if any one can provide me any method or js script that will work plz come forward and drop here.

def mouseUI(page: Page) -> None:
    page.add_init_script("""
        (() => {
            const dot = document.createElement('div');
            dot.id = '__mouse_dot__';
            Object.assign(dot.style, {
                position: 'fixed',
                width: '8px',
                height: '8px',
                borderRadius: '50%',
                backgroundColor: 'red',
                zIndex: '2147483647',  // Max z-index
                pointerEvents: 'none',
                top: '0px',
                left: '0px',
                transform: 'translate(-50%, -50%)',
                transition: 'top 0.03s linear, left 0.03s linear'
            });
            document.body.appendChild(dot);

            window.addEventListener('mousemove', e => {
                dot.style.left = `${e.clientX}px`;
                dot.style.top = `${e.clientY}px`;
            });
        })();
    """
)

i tried out this method although it did not worked . also i am expecting a mouse UI js or something that can enable a pointer in my chromium playwright browser so that i can visually see my mouse pointer pointing and analyize it [speed , clicking, moving , static]

0

3 Answers 3

2

add_init_script runs before the document loads, but if you wait for the "DOMContentLoaded" event per this answer, your DOM changes will take effect.

Here's a demonstration:

from playwright.sync_api import sync_playwright # 1.53.0
from random import randint
from time import sleep


js = """
window.addEventListener('DOMContentLoaded', () => {
  const dot = document.createElement('div');
  dot.id = '__mouse_dot__';
  Object.assign(dot.style, {
    position: 'fixed',
    width: '8px',
    height: '8px',
    borderRadius: '50%',
    backgroundColor: 'red',
    zIndex: '2147483647',  // Max z-index
    pointerEvents: 'none',
    top: '0px',
    left: '0px',
    transform: 'translate(-50%, -50%)',
    transition: 'top 0.03s linear, left 0.03s linear'
  });
  document.body.appendChild(dot);
  window.addEventListener('mousemove', e => {
    dot.style.left = `${e.clientX}px`;
    dot.style.top = `${e.clientY}px`;
  });
});
"""

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.new_page()
    page.add_init_script(js)
    page.goto("https://www.example.com", wait_until="commit")

    for _ in range(10):
        page.mouse.move(randint(0, 500), randint(0, 500))
        sleep(1)

    browser.close()

See also: How to Create a Mouse Trail Effect in Playwright for Random Mouse Movements?

Sign up to request clarification or add additional context in comments.

Comments

-2

🔧 1. Use evaluate() after navigation instead of add_init_script()

from playwright.sync_api import sync_playwright, Page

# Function to inject red mouse pointer UI
def mouse_ui_overlay(page: Page):
    js_script = """
        (() => {
            const dot = document.createElement('div');
            dot.id = '__mouse_dot__';
            Object.assign(dot.style, {
                position: 'fixed',
                width: '10px',
                height: '10px',
                borderRadius: '50%',
                backgroundColor: 'red',
                zIndex: '9999999',
                pointerEvents: 'none',
                top: '0px',
                left: '0px',
                transform: 'translate(-50%, -50%)',
                transition: 'top 0.05s linear, left 0.05s linear'
            });
            document.body.appendChild(dot);

            window.addEventListener('mousemove', (e) => {
                dot.style.left = `${e.clientX}px`;
                dot.style.top = `${e.clientY}px`;
            });

            window.addEventListener('mousedown', () => {
                dot.style.backgroundColor = 'blue';
            });
            window.addEventListener('mouseup', () => {
                dot.style.backgroundColor = 'red';
            });
        })();
    """
    page.evaluate(js_script)

# Main script
with sync_playwright() as p:
    browser = p.chromium.launch(headless=False, slow_mo=100)  # Show browser UI + slow motion
    context = browser.new_context()
    page = context.new_page()
    
    page.goto("https://example.com")  # Any URL you want
    
    mouse_ui_overlay(page)  # Show red dot mouse pointer overlay
    
    # Simulate some mouse actions (you’ll see the red dot move)
    page.mouse.move(150, 150)
    page.mouse.click(150, 150)
    page.mouse.move(300, 300)
    page.mouse.down()
    page.mouse.up()

    page.wait_for_timeout(5000)  # Keep browser open for 5 seconds

    browser.close()

1 Comment

hm why evaluate ?
-2
from playwright.sync_api import sync_playwright, Page
import time

def enable_mouse_ui(page: Page) -> None:
    """
    Injects a script into the page to display a visual mouse pointer.

    This helper is useful for debugging human-like automation scripts,
    allowing you to see the mouse's position and interactions.
    """
    mouse_helper_script = """
        (() => {
            const box = document.createElement('div');
            box.classList.add('mouse-helper');
            const styleElement = document.createElement('style');
            styleElement.innerHTML = `
            .mouse-helper {
                pointer-events: none;
                position: absolute;
                top: 0;
                left: 0;
                width: 20px;
                height: 20px;
                background: rgba(255, 0, 0, 0.4);
                border: 1px solid white;
                border-radius: 10px;
                margin: -10px 0 0 -10px;
                padding: 0;
                transition: background .2s, border-radius .2s, border-color .2s;
                z-index: 10000;
            }
            .mouse-helper.button-1 {
                transition: none;
                background: rgba(0, 0, 0, 0.9);
            }
            .mouse-helper.button-2 {
                transition: none;
                border-color: rgba(0, 0, 255, 0.9);
            }
            .mouse-helper.button-3 {
                transition: none;
                border-radius: 4px;
            }
            `;
            document.head.appendChild(styleElement);
            document.body.appendChild(box);

            addEventListener('mousemove', event => {
                box.style.top = `${event.clientY}px`;
                box.style.left = `${event.clientX}px`;
            }, true);

            addEventListener('mousedown', event => {
                box.classList.add(`button-${event.which}`);
            }, true);

            addEventListener('mouseup', event => {
                box.classList.remove(`button-${event.which}`);
            }, true);
        })();
    """
    page.add_init_script(mouse_helper_script)

def main():
    """
    Example usage of the mouse UI helper.
    """
    with sync_playwright() as p:
        # Launch the browser in non-headless mode to see the UI
        browser = p.chromium.launch(headless=False, slow_mo=100)
        page = browser.new_page()

        # Enable the visual mouse pointer before navigating
        enable_mouse_ui(page)

        page.goto("https://playwright.dev")

        # Demonstrate mouse movements and actions
        print("Moving mouse...")
        page.mouse.move(100, 200)
        time.sleep(1)

        print("Moving to 'Get Started' button and clicking...")
        get_started_button = page.get_by_role("link", name="Get started")
        button_box = get_started_button.bounding_box()

        if button_box:
            # Move mouse to the center of the button
            page.mouse.move(
                button_box['x'] + button_box['width'] / 2,
                button_box['y'] + button_box['height'] / 2
            )
            # Click and observe the visual feedback
            page.mouse.down()
            time.sleep(0.5)
            page.mouse.up()
            get_started_button.click()
        
        page.wait_for_load_state()
        print("Page navigated. The mouse pointer should still be visible.")
        time.sleep(3)

        browser.close()

if __name__ == "__main__":
    main()

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
i will try it .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.