Sunday, April 19, 2015

"Why Won't Mobile Safari Write Cookies for My Web Site?"

Probably because, as I was, you're triggering your cookie Javascript with "onunload" or "onbeforeunload." That won't work on Safari for iPad or iPhone.

Modern browsers work differently from older ones -- they want to save your page off-screen, or "cache" it, rather than unload it completely. In some browsers, your use of "onunload" or "onbeforeunload" rules out caching, leading to slower performance for your site. Safari on iOS, on the other hand, caches the page anyway and just ignores your script!

The solution is simple. In place of "onunload" or "onbeforeunload," use "onpagehide." That's right, just substitute that one term for either of the other two. Then your script will be triggered whenever the page is unloaded OR just cached. Not only will Safari now write your cookies, but this will speed up navigation back to your page in all other modern browsers!

By the same token, you may want to replace "onload" with "onpageshow." But not always. "Onpageshow" will trigger whenever a page is loaded OR just retrieved from cache. But if the page is just retrieved, it returns in its previous state, so onload functions may not be needed or wanted. In that case, you should leave those functions in "onload," while moving any others to "onpageshow."

The biggest disadvantage to using the new triggers is that older browsers won't recognize them. That includes Internet Explorer before version 11. If that's important to you, you can design your JavaScript to revert to the older triggers for older browsers. (But I haven't bothered.)

No comments:

Post a Comment