gpt4 book ai didi

ios - 使用WKWebView读取本地存储数据

转载 作者:行者123 更新时间:2023-11-28 23:19:31 24 4
gpt4 key购买 nike

我需要读取存储在 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)

最佳答案

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

  • 您的 WKWebView 需要分配 navigationDelegate

    webView.navigationDelegate = self

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

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

关于ios - 使用WKWebView读取本地存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59838909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com