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.

squeak
  • 33
  • 1
  • 1
  • 5
  • 1
    can you post your html with the button – I am Cavic Jan 10 '14 at 16:39
  • 3
    You **leave** the page with `window.location`. – elclanrs Jan 10 '14 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. – gen_Eric Jan 10 '14 at 16:39
  • 2
    You can't click a button on another webpage. That would allow malicious people to do awful things. – Trevor Dixon Jan 10 '14 at 16:39
  • When you do `window.location="url"`, are you sending the user to another page you control, or some other website? If it's a page you own, there are other things you can do to solve this problem. – Trevor Dixon Jan 10 '14 at 16:41
  • 1
    Some dups: http://stackoverflow.com/questions/7493847/is-is-possible-to-call-a-function-after-window-location-has-loaded-new-url, http://stackoverflow.com/questions/18048338/how-can-i-execute-a-script-after-calling-window-location-href, http://stackoverflow.com/questions/15276070/how-to-run-code-after-changing-the-url-via-window-location – elclanrs Jan 10 '14 at 16:42
  • Thank you. I believe the linked duplicates can sufficiently answer my question. Can this question be removed? – squeak Jan 11 '14 at 17:56

3 Answers3

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>
kuroi neko
  • 8,479
  • 1
  • 19
  • 43
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.

Anthed
  • 139
  • 1
  • 6
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();
}
Xiphias
  • 4,468
  • 4
  • 28
  • 51