简体   繁体   中英

How does one click a button on a webpage using Javascript?

I have created an HTML file that runs the following JavaScript function:

    window.location="url";
    document.getElementById('button-id').click();

The script loads the webpage as mentioned in the url. However, it does not respond to the second statement ie the click. I ran the same code via the Chrome JavaScript Console and it worked perfectly.

If you load a new URL, how to find the element "button-id" that used to exist on the first page ? If this element exists on the second page, use document.onload or $(document).ready() with jquery to execute automatically the action associated to your "click" action.

Omit window.location before your trigger. On this page, document.getElementById('nav-questions').click() works, for example.

In your case, if it is necessary to write these to statements together, seperate the two lines using a control flow like if or something similar. When the click() should be exectued, there must not be a window.location before.

Example:

if (redirect) {
    window.location = url;
} else {
    document.getElementById('nav-questions').click();
}

This will not work before the document is done loading.

It works from the console because the document has long been loaded, but when the browser executes it, it's too early.

Try this as a proof of concept:

<body onload='document.getElementById('clickme').click();'>
<button type='button' id='clickme' onclick='window.location="wherever";'>
</body>

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