cfly24
cfly24

Reputation: 1952

LocalStorage not working on iPhone - Not in Private Browsing

I am trying to Save user input from a textarea in localstorage on the unload of a page and then read it back into a textarea when the user returns. It is working fine in a desktop browser, but doesn't seem to be working on my iPhone. This is not the same as the Private Browsing issues that have been previously answered.

Here is the html:

<html>
 <head>
  <title>Cookie Test</title>
  <link rel="stylesheet" type="text/css" href="css/site.css">
 </head>
 <body class="full" onload="getText()" onunload="saveText()">
  <div class="fullscreen-overlay" id="fullscreen_overlay">
  <div class="fullscreen-container js-fullscreen-container">
  <div class="textarea-wrap">
  <textarea name="fullscreen-contents" id="fullscreen-contents"></textarea>
  </div>
  </div>
  </div>
 </body>
</html>

And the Javascript to get and write to localstorage:

var text = document.getElementById('fullscreen-contents');

function saveText() {
  localStorage.savedText = text.value;
  console.log("saved");
}

function getText() {
  if (localStorage.savedText) {
    text.value = localStorage.savedText;
    console.log("loaded");
  }
}

This is happening in iOS 8 and Private Browsing is not turned on. Any idea what could be going on? Thanks!

Upvotes: 1

Views: 2683

Answers (2)

AHSAN KHAN
AHSAN KHAN

Reputation: 436

sessionStorage.setItem('some Key', 'some value');

This may not work on some iPhone and iPad OS versions

best solution is to put this code in try and catch so code after this can run

 try {
        sessionStorage.setItem('some Key', 'some value');

 }catch(ex) {
    // iOS 8.3+
    /*Does not support session Storage Correctly;
    alert('unsupported'+ex);*/

   }

Upvotes: 0

Alvaro Montoro
Alvaro Montoro

Reputation: 29625

Use onpageshow and onpagehide instead of onload and onunload.

According to the iOS developer library (and same for the Safari documentation), the load and unload events are deprecated, and it recommends to use pageshow and pagehide respectively:

The load and unload events may not work as expected for back and forward optimization. Use the pageshow and pagehide events instead.

Upvotes: 2

Related Questions