iOS wkwebview怎么寫localStorage

iOS中WKWebView,存在首次加載h5頁面,h5頁面中的js就拿不到localstorage了。

WKWebView localStorage 緩存很嚴重

HTML5在客戶端存儲數(shù)據(jù)的方式:cookie , localStorage, sessionStorage
cookie:只能存儲少量的數(shù)據(jù), 常用來存儲賬號密碼等
localStorage : 沒有時間限制的數(shù)據(jù)存儲
sessionStorage : 針對一個 session 的數(shù)據(jù)存儲, 當網(wǎng)頁關閉時,數(shù)據(jù)也會被刪除。

1.WKWebView設置localStorage
NSString * userContent = [NSString stringWithFormat:@"{"token": "%@", "userId": %@}", @"a1cd4a59-974f-44ab-b264-46400f26c849", @"89"];
// 設置localStorage
NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('userContent', '%@')", userContent];
// 移除localStorage
// NSString *jsString = @"localStorage.removeItem('userContent')";
// 獲取localStorage
// NSString *jsString = @"localStorage.getItem('userContent')";
[self.webView evaluateJavaScript:jsString completionHandler:nil];

NSString * userContent = @"{"name": "Tom", "age": 10}"];
// 設置localStorage
NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('userContent', '%@')", userContent];
// 移除localStorage
// NSString *jsString = @"localStorage.removeItem('userContent')";
// 獲取localStorage
// NSString *jsString = @"localStorage.getItem('userContent')";
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
//清理掉所有的localStorage數(shù)據(jù)
//NSString *clearString = @"localStorage.clear()";

iOS wkwebview localstorage數(shù)據(jù)處理

WKWebView 在內存占用上優(yōu)化的很多。但是在實踐中發(fā)現(xiàn)bug:localstorage信息不一致。

A頁面和B頁面都存在 一個WKWebView。 在B頁面使用localstorage保存信息。 回到A頁面取不到最新的數(shù)據(jù)。

原因:

https://developer.apple.com/reference/webkit/wkwebviewconfiguration 中有個屬性 processPool,描述是:The process pool from which to obtain the view’s Web Content process.

解決方法:

把config中的processPool變?yōu)閱卫蚕?/p>

  • (WKProcessPool*)singleWkProcessPool{

    staticWKProcessPool*sharedPool;

    staticdispatch_once_tonceToken;

    dispatch_once(&onceToken, ^{

      sharedPool = [[WKProcessPoolalloc]init];
    

    });

    returnsharedPool;

}

設置webview的配置 config.processPool = [NYWKWebView singleWkProcessPool];

Local Storage存在的問題

在查詢資料的過程中,發(fā)現(xiàn)了很多Local Storage的缺陷,有一篇關于Local Storage的論文可以參考。有以下幾點:

  1. 不要用Local Storage來做持久化存儲,在iOS中,出現(xiàn)存儲空間緊張時,它會被系統(tǒng)清理掉;
  2. 不要用Local Storage來存大量數(shù)據(jù),它的讀寫效率很低下,因為它需要序列化/反序列化;
  3. 大小限制為5M

webview 和 iframe 有什么區(qū)別?

webview是網(wǎng)頁的原生載體,用于在原生環(huán)境中加載一個頁面,iframe是網(wǎng)頁的html載體,用于在網(wǎng)頁中加載一個頁面

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容