简体   繁体   中英

How do I automate clicking a button in javascript?

my current work is basically clicking a button every couple of minutes and check if there are any new tickets.

With some programming background I thought this would be an easy-to-automate task, but being completely new to javascript, I'm already struggling with the "button clicking".

Unfortunately, because it is an internal website, I can't share the exact code, but I'll try to give as much information as I am able to.

I tried to "click" in the console:

'document.getElementById("IDofButton").click()'

But it gives me an error "undefined"; without the ".click()" at the end I get the correct element as a result. I tried it with "$" instead of document.getElementById, but even that didn't work, so I gave up on the idea of simply clicking the button, even though I think that's the easier way.

Debugging in chrome with breakpoints and the performance profiler, I could find the first called function "h()", it runs for 0.020 ms, then another function gets called, running for 0.012 ms and then a longer function gets called running for 14.8 ms, several others follow. My guess or better hope, was that the first two functions check something and then start the whole process. But I can't simply call any of the functions with like the following example syntax: "h()".

I'd be very glad, if anyone has an idea or could point me in the right direction. Thank you very much.

EDIT/UPDATE:

I finally found the problem: While debugging with the performance profiler I saw, that the functions are triggered by a mouseup event and I thought the "[...].click()" simulates a mousedown and a mouseup instead of a click. I now copied a function simulating the whole mouseover>mousedown>mouseup>click and it works as expected.

Thank you to all who helped me with the whole situation!


setInterval(

function(){

document.getElementById('IDofButton').click()

},5000)// time in milliseconds i set for 5 sec

Above time set for each 5 Seconds.

if doesn't work Let me know.

You get undefined because your selector is wrong. Try learning css selectors and see if it helps you( https://www.w3schools.com/cssref/css_selectors.asp )

You can also inspect the elements in the dev tools and right clicking on the element, going to copy->Copy JS Path. This will give you the correct selector.

Also you can select the element and reference it in the dev tools console with $0.

Then if you want to re-click every second then use setInterval

setInterval(() => {
    document.querySelector('#someId').click()
}, 1000)

Hope that helps you, good luck!

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