[英]HTML5 localStorage.setItem is not working on iOS 8 - Safari mobile
localStorage.setItem
在移動iOS 8.3上不起作用。
有人遇到這個問題嗎?
這是代碼:
var storage = window.localStorage;
storage.setItem('test',45);
alert(storage.getItem('test'));
過去,我們可以使用類似:
if ('localStorage' in window && window.localStorage !== null) {
alert('can use');
}else{
alert('cannot use');
}
要么
if (localStorage === undefined) {... }
但是,在iOS 8.3+中,當用戶禁用cookie時 ,此代碼將引發未處理的JavaScript錯誤。 當用戶進入私有瀏覽模式時 ,當您嘗試寫入localStorage時,也會出現相同的錯誤消息。
SecurityError:DOM異常18:試圖突破用戶代理的安全策略。
解決方法
為了避免由於iOS的這種特殊行為而導致不必要的JavaScript錯誤,一種建議是將其包含在try catch塊中。 (至少暫時)
try{
if ('localStorage' in window && window.localStorage !== null) {
localStorage.setItem('testLocalStorage', 'testLocalStorage');
if (localStorage.getItem('testLocalStorage') !== 'testLocalStorage') {
localStorage.removeItem('testLocalStorage');
//for private browsing, error is thrown before even getting here
alert('can read CANNOT write');
}else{
localStorage.removeItem('testLocalStorage');
alert('can use');
}
}else{
alert('CANNOT use');
}
}catch(ex){
alert('CANNOT use reliably');
}
注意:建議不要在實際代碼中使用警報。 這只是為了快速說明。
可能的縮寫
try {
localStorage.setItem('testLocalStorage', 'testLocalStorage');
localStorage.removeItem('testLocalStorage');
alert('supported');
} catch(ex) {
alert('unsupported');
}
我們可以用什么代替
對於不支持localStorage的方案,可能的替代方案包括服務器會話(如果不支持cookie,則基於URL參數),或用於存儲序列化數據的window.name變量。
或者,如果您設計和構建為單頁應用程序,則可能根本不需要將數據存儲在全局命名空間中。
您應該使用以下代碼檢查localStorage是否可用,例如if ('localStorage' in window && window.localStorage !== null) { ...
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.