squeak
squeak

Reputation: 33

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 i.e. the click. I ran the same code via the Chrome JavaScript Console and it worked perfectly.

Upvotes: 3

Views: 22383

Answers (3)

kuroi neko
kuroi neko

Reputation: 8661

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>

Upvotes: 1

Xiphias
Xiphias

Reputation: 4716

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();
}

Upvotes: 0

Anthed
Anthed

Reputation: 139

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.

Upvotes: 0

Related Questions