WKWebView存储数据到localStorage

项目中需要在webView的localStorage存入一下数据,参考网上的文章写了两个方法

    /// 设置
    /// - Parameters:
    ///   - key: 键
    ///   - json: 值
    func setLocalStorage(key: String, json: [String: Any]) {
        guard let jsonStr = json.toJsonString() else { return }
        let jsString = String.init(format: "localStorage.setItem('" + key + "', '%@')", jsonStr)
        webView.evaluateJavaScript(jsString) { (data, error) in
            QSLog(data ?? "")
            QSLog(error ?? "")
        }
    }
    
    /// 获取
    /// - Parameter key: 键
    func getLocalStorage(key: String) {
        let jsString = "localStorage.getItem('" + key + "')"
        webView.evaluateJavaScript(jsString) { (data, error) in
            QSLog(data ?? "")
            QSLog(error ?? "")
        }
    }

在webView加载完成后进行设置才有效

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    let testDict = ["token": "test"]
    setLocalStorage(key: "test", json: testDict)
    getLocalStorage(key: "test")
}

参考文章:
iOS WKWebview首次加载LocalStorage 问题解决经历

你可能感兴趣的:(WKWebView存储数据到localStorage)