Search code examples
javascriptjquerylocal-storagehubspot

How to recover a value from localStorage in JavaScript on mobile devices?


I am saving a value in localStorage on my first page (first.html) like below:

const localStorage = window.localStorage;
localStorage.setItem('entered_email', $form.find('input[name="email"]').val());

Then on my second page (second.html), I am trying to retrieve the value and write it inside a span element.

The code looks like below:

<span id="email_entered"></span>

<script>
    $(document).ready(function() {
        $("#email_entered").text(localStorage.getItem('entered_email'));
        localStorage.removeItem("key");
        localStorage.clear()
    });
</script>

The code works pretty well on desktop and I get the entered email on the other page but when it comes to mobile devices, I get null.

By the way, $form.find('input[name="email"]').val()); is related to a HubSpot form which is written on first.html and when it is submitted, redirects the user to second.html. I have written the code inside the onFormSubmitted function of the relevant HubSpot form. The complete code looks like below:

<script>
    hbspt.forms.create({
        region: "eu1",
        portalId: "xxxxxxxx",
        formId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        onFormSubmitted: function($form) {
            const localStorage = window.localStorage;
            localStorage.setItem('entered_email', $form.find('input[name="email"]').val());
        }
    });
</script>

Is there a way to solve this issue on mobile devices?


Solution

  • I solved the issue by using sessionStorage instead of localStorage. And one interesting point that I noticed after @Peter Krebs comment, was moving the line of code which retrieves the value from sessionStorage outside the $(document).ready(function () {...});

    Therefore, the final code looks like below in first.html:

    <script>
        hbspt.forms.create({
            region: "eu1",
            portalId: "xxxxxxxx",
            formId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
            onFormSubmitted: function($form) {
                sessionStorage.setItem("entered_email", $form.find('input[name="email"]').val());
            }
        });
    </script>
    

    and like below in second.html:

    <span id="email_entered"></span>
    <script>
        $("#email_entered").text(sessionStorage.getItem('entered_email'));
    </script>