1

I want to redirect my browser to another website and then click on a action button on that website. I think i should add some time delay in between these two tasks. The code i have written do only one event at a time.

window.location.href = "http://www.google.com";
var delayInMilliseconds = 2000; 
setTimeout(function() {
  document.getElementById('action-button').dispatchEvent(new MouseEvent("click"));
}, delayInMilliseconds);

3 Answers3

3

It's forbidden to do this for security reasons.

In computing, the same-origin policy is an important concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. An origin is defined as a combination of URI scheme, host name, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.

Source

Himansh
  • 879
  • 9
  • 15
1

It is not possible in this manner.

First you change the url of the page which will stop the rest of your JS code from executing. So your timeout will never reach the google page.

Instead implement an <iframe> with the src set to http://www.google.com. Then select the iframe and look for your element in there.

This post will explain how to select the element from an iframe.
Get element from within an iFrame

Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
  • I cannot be sure, but I don't think OP will deploy his script on the same domain as google.com. same-origin policy need to apply for that to work. – Federkun Aug 18 '19 at 12:24
  • google is just used as an example here. I am trying the stuff on a different wensite – Deepanshu jindal Aug 18 '19 at 12:26
  • @Deepanshu jindal, still what Federkun says applies here. If the other website is on the same domain it will work. – Emiel Zuurbier Aug 18 '19 at 12:31
  • Seems like this is controlled by the embedded page through this header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options (and indeed google has this configured to sameorigin) – Michael Aug 18 '19 at 12:35
0

At the moment you redirect the user with window.location.href any other script won't be executed.

Sort of hack to do what you want is implant script on the second website that will trigger if the user came from a specific URL. Something like that:

var URL = "OLDWEBSITEURL";
var x = window.history.back();
if (x === URL) {
  document.getElementById('action-button').dispatchEvent(new MouseEvent("click"));
/* or any other code */
}

Note that if the user open the link on different window/tab or/and disable js it won't work.

A. Meshu
  • 4,053
  • 2
  • 20
  • 34