简体   繁体   中英

How can I detect url change in JQuery?

What I'm trying to do is to flush localStorage when user move to other page.

For example, let say I'm currently in http://foo.com/accounts/mypage .

When user moves to url, http://foo.com/album , I want to flush localStorage .

This is my JQuery script.

$(window).unload(function(){
    if ((window.location.pathname).indexOf('mypage') < 0) {
        localStorage.flush();
    }
});

But it doesn't work......

Any other nice idea?

localStorage.clear();

请试试这个

Add a click handler to your links, like this:

var lastLink = "";
$("body").on("click", "a", function() {
    lastLink = $(this).attr("href");
});

This click will run before the unload event and you will be able to use lastLink as your value. Just make sure you take into account relative urls as well.

//TODO: implement function isMine
$(window).unload(function() {
    if (isMine(lastLink)) {
        localStorage.clear();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM