-1

Today use this Code but this code some time not properly work

Problem : Page refresh then call unload() but some time user change URL directly at that time not call unload() because website change...

So, How to solve it in all Browser. Please Help Me

<html>
    <head>
        <script type="text/JavaScript">
            function unload(){
                alert("My Page unLoad - Destroy Variable");
            }

            function load() {
                alert("My Page Load");
            }
        </script>
    </head>

    <body onLoad="load()">
        <script type="text/javascript">
            window.onbeforeunload = unload();
        </script>
    </body>
</html>
8
  • 1
    You don't need to destroy or null variables in Javascript. That already happens when the page changes. Commented Oct 2, 2016 at 8:11
  • Yes, You are Right. But I am use localStorage Variable So, not Destroy automatically... manually destroy it. Commented Oct 2, 2016 at 8:38
  • So you want to remove data from localStorage when you leave the page? It simply sounds like you should be using variables instead. If this isn't the case then you need to clearly explain what you're trying to do and what the problem is, rather than give us snippets until we finally get to the problem. Commented Oct 2, 2016 at 8:39
  • yes remove data from localStorage when you leave the page via url change.... Commented Oct 2, 2016 at 9:31
  • 1
    You shouldn't be using localStorage. Commented Oct 2, 2016 at 9:38

1 Answer 1

2

HTTP is stateless, so on every new page the variables will begin in their uninitialised state, and all code set to run on load (ie. not in an event handler) will run.

If you are using localstorage:

Check this question on how to detect changes in the url: How to detect URL changes with jQuery

Then use this to destroy it:

 window.localStorage.removeItem(key);
Sign up to request clarification or add additional context in comments.

2 Comments

But I am use localStorage Variable... So, not Destroy... manually destroy
URL change at that time not work this solution. this solution already use but not proper work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.