Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute some jQuery or JavaScript code after a redirect has completed

How can I execute jQuery/JS code as soon as a jQuery/JS redirect like...

$(location).attr('href','/target_path');

...or...

window.location.href = "/target_path";

...has finished loading the new page?

Specifically, I need to pass an alert message and insert it into and display it (enclosed in some HTML) on the new page.

like image 590
TomDogg Avatar asked Feb 17 '23 15:02

TomDogg


2 Answers

You can't. Once the redirect happens you are no longer on that page. You can't execute code on a page you are no longer on. If you want the next page to do something then you need to pass, either by cookie or URL parameter, a flag that instructs it to do so.

like image 50
John Conde Avatar answered May 09 '23 16:05

John Conde


It is impossible to tell JavaScript to execute some code after a redirect.

However you have different options:

  1. Pass a string in the redirect URL and then do something on "ready"
  2. Store some information in a cookie and then do something on "ready"
  3. Store some data using DOM storage (namely sessionStorage) if you don't mind the smaller browser support
like image 26
MMM Avatar answered May 09 '23 17:05

MMM