简体   繁体   中英

How to simulate a long mouse left click

I'm doing a little jquery script that help me doing some stuff when I'm not at my computer. Something like a bot.

This bot must perform some left-click on specific X,Y points of a page.

I use this code and works perfectly: document.elementFromPoint(X, Y).click();

But I also need to do a long click on another point of the page. I need to simulate this: Press left click at (x,y) ... Wait 3 seconds ... Release left click.

Is there a way to do something like that ?

Thank you.

Using pure JavaScript, this might not be possible. At least not for all circumstances.

However, if the element you're targeting is using mousedown and mouseup to detect this "long mouse click", then you could possibly trigger them directly:

document.elementFromPoint(X, Y).mousedown();

setTimeout(() => document.elementFromPoint(X, Y).mouseup(), 3000);

Like I said, won't work in all circumstances, since you aren't actually controlling the mouse itself, but should let you simulate it in some.

Put a timeout listener between mousedown and mouseup

Not the best code, but you could do something like this:

function listenForLongClick (domElement, timeout = 3000) {
    let mouseDownStarted = false;
    let timeoutCheck = null;
    domElement.addEventListener('mousedown', () => {
        mouseDownStarted = true;

        timeoutCheck = setTimeout(() => mouseDownStarted = false, timeout);
    }, false);
    domElement.addEventListener('mouseup', () => {
        clearTimeout(timeoutCheck);

        if (mouseDownStarted) { console.log('within the 3 seconds'); }

        mouseDownStarted = false;
    }, false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM