使用WKWebView读取本地存储数据

Read local storage data using WKWebView

我需要读取存储在 WKWbview 本地存储中的值。 我尝试使用下面的代码但没有得到。 我能够在本地存储中写入值,但难以从中读取值。

  let script = "localStorage.getItem('token')"
        wkWebView.evaluateJavaScript(script) { (token, error) in
            print("token = \(token)")
        }

WKWebView 初始化代码:

    // 1
    let accessToken = UserDefaults.standard.value(forKey: "token") as? String
    // 2
    let refreshToken = UserDefaults.standard.value(forKey: "RefreshToken") as? String
    // 3
    let configuration = WKWebViewConfiguration()
    // 4
    let contentController = WKUserContentController()
    let accessTokenScript = "javascript: localStorage.setItem('token', '\(accessToken!)')"
    // 5
    let userAccessTokenScript = WKUserScript(source: accessTokenScript, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)

    // 6
    contentController.addUserScript(userAccessTokenScript)
    configuration.userContentController = contentController
    self.wkWebView = WKWebView(frame: controller.view.bounds, configuration: configuration)

您需要在网站已经加载时注入此脚本:

  • 您的 WKWebView 需要分配 navigationDelegate

    webView.navigationDelegate = self

  • 在网站完全加载时注入脚本

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    
    //you might want to edit the script, with the escape characters
    let script = "localStorage.getItem(\"token\")"
    wkWebView.evaluateJavaScript(script) { (token, error) in
        if let error = error {
            print ("localStorage.getitem('token') failed due to \(error)")
            assertionFailure()
        }
        print("token = \(token)")
    }
}