How can I execute jQuery/JS code as soon as a jQuery/JS redirect like...
$(location).attr(\'href\',\'/target_path\');
...or...
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.
It is impossible to tell JavaScript to execute some code after a redirect.
However you have different options:
sessionStorage
) if you don't mind the smaller browser supportYou can't do that in the page that's redirecting. You can read the referrer in the landing page (document.referrer
), and then decide whether to display an alert based on that, though.
var x = "It's some text";
var loc = '/target_path';
loc += '?message=' + encodeURI(x);
The JS file on the new page can then look at the query string to see if a message is there, and do the required action if it's detected.
You can use window.location.search
on the new page to see what's there, although I'd recommend hunting for a deparam function in a library to turn the query string into a more usable object.