Can you detect when a user is navigating away?

Hello Everyone,

This is my first post and I’m new to the forums so I apologize if I missed this in searching. Is it possible to detect when the user is navigating to a different link and run some logic before that happens? I’ve seen some posts about using onbeforeunload but I couldn’t get it to work.

I have some values stored in localStorage that I want to clear before the user navigates away to another URL. I’ve posted an example of what I had before that wasn’t working. It’s absolutely possible I’m not using it correctly so any help or suggestions would be appreciated. I’m happy to provide more detail if needed I just didn’t want this to be ridiculously long. Thanks.

window.onbeforeunload = function(event) {
  localStorage.removeItem("vuex");
}

Note: I don’t want to prevent the user from leaving and I would need this to work from any component or view.

Can you define this? Navigating away from the current domain or navigating within it?

If navigating away from the current domain, then window.onbeforeunload should work, though it’s generally preferred to use window.addEventListener('beforeunload', function (e) { });

In this case it would be navigating within the current domain. It’s possible that it may have been the placement of where I had the code. I wasn’t sure where to trigger it so I placed it on the component I wanted to test on inside of the <script> tag just after the imports.

So, the actual issue had nothing to do with the listener at all. I needed to clear sessionStorage not localStorage.