前言
前階段,測試提了個bug,在蘋果手機中無痕模式下,搜索按鈕很差使,沒法跳頁,同時搜索歷史也沒有展現(用戶搜索歷史時使用localStorage存儲)。
正文
iOS上Sarfari在無痕模式下,瀏覽器僞裝支持localStorage,並在全局window上暴漏了該方法,因此校驗是有localStorage對象的,可是調用setItem進行保存的時候,就報
Error: QuotaExceededError ... : The quota has been exceeded.
所以,進行了個小測試......,可能測試不夠全面!
1.測試機型
iPhone7 Plus 版本 11.3
iPhone6 Plus 版本 11.3.1
iPhone6 版本 10.2.1
iPhoneSE 版本 9
oppe r9
2.測試瀏覽器
Sarfari UC 自帶瀏覽器
3.結果:
iOS9,iOS10 Sarfari
setItem 報錯
getItem null
iOS 11 Sarfari
setItem 可set
getItem 可get
iOS 11 UC
setItem 不可set,但不報錯
getItem null
安卓機
可set,可get
4.結論:
只有iOS九、10還存在無痕瀏覽下localStorage沒法使用的狀況,iOS11中Sarfari已支持存取localStorage,可是iOS11中UC不支持存localStorage。
因此,在開發過程當中使用loaclStorage就須要對以上狀況進行兼容,避免 js 報錯後影響整個頁面的功能。
5.解決代碼及注意要點:
1.使用try/catch
2.只針對setItem,進行判斷「瀏覽器是否開啓無痕模式」
//判斷瀏覽是否支持localStorage
function isLocalStorageSupport{
try {
var isSupport = 'localStorage' in window && window['localStorage'] !== null;
if (isSupport) {
localStorage.setItem("local_storage_test", "1");
localStorage.removeItem("local_storage_test");
}
return isSupport;
} catch (e) {
return false;
}
}
//判斷瀏覽器是否開啓無痕模式
function isInPrivate(){
try {
localStorage.setItem("local_storage_test", "1");
localStorage.removeItem("local_storage_test");
return false;
} catch(e){
return true;
}
}