Read local storage data using WKWebView

血红的双手。 提交于 2021-01-28 19:06:26

问题


I need to read value stored in the local storage of WKWbview. I tried using the below code but getting nil. I am able to write values in local storage but facing difficulty in reading values from it.

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

WKWebView init code:

    // 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)

回答1:


You need to inject this script when the website has already loaded:

  • your WKWebView needs to assign the navigationDelegate

    webView.navigationDelegate = self

  • inject the script when the website was loaded completely

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)")
    }
}


来源:https://stackoverflow.com/questions/59838909/read-local-storage-data-using-wkwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!