问题
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