使用 WKWebView 读取本地存储数据 [英] Read local storage data using WKWebView

查看:25
本文介绍了使用 WKWebView 读取本地存储数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要读取存储在 WKWbview 本地存储中的值.我尝试使用下面的代码但得到零.我能够在本地存储中写入值,但在从中读取值时遇到困难.

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 初始化代码:

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)

推荐答案

需要在网站已经加载时注入这个脚本:

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

  • 您的 WKWebView 需要分配 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)")
    }
}

这篇关于使用 WKWebView 读取本地存储数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆