简体   繁体   中英

Clear sessionStorage when user navigates away?

I have sessionStorage.setItem that triggers when someone clicks a button.

sessionStorage.setItem('save', saved);

That's nice, but is there a way with jQuery to delete this sessionStorage upon user navigating away from the page in any way?

The answer I found so far. . .

$(window).on("beforeunload", function() {
    $.ajax("someURL", {
        async: false,
        data: "test",
        success: function(event) {
             console.log("Ajax request executed");
        }
    });
    return "This is a jQuery version";
});

. . . had way complicated-seeming AJAX.

But I am finding some simpler way to do this?

Why would you need AJAX? Just use beforeunload event and clear sessionStorage item?

$(window).on("beforeunload", function() {
sessionStorage.removeItem('save'); 
});

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