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

后端 未结 4 1623
心在旅途
心在旅途 2021-01-20 00:21

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

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

...or...



        
相关标签:
4条回答
  • 2021-01-20 01:00

    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.

    0 讨论(0)
  • 2021-01-20 01:16

    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
    0 讨论(0)
  • 2021-01-20 01:18

    You 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.

    0 讨论(0)
  • 2021-01-20 01:21
    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.

    0 讨论(0)
提交回复
热议问题