3

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.

7
  • 1
    can you post your html with the button Commented Jan 10, 2014 at 16:39
  • 3
    You leave the page with window.location. Commented Jan 10, 2014 at 16:39
  • 1
    You can't do this. Your page cannot run code on another page. Once you do window.location, your page is unloaded and the new one is loaded. What you want is impossible. Commented Jan 10, 2014 at 16:39
  • 2
    You can't click a button on another webpage. That would allow malicious people to do awful things. Commented Jan 10, 2014 at 16:39
  • 1
    Some dups: stackoverflow.com/questions/7493847/…, stackoverflow.com/questions/18048338/…, stackoverflow.com/questions/15276070/… Commented Jan 10, 2014 at 16:42

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

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.