Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read local storage data using WKWebView

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)
like image 891
ak_tyagi Avatar asked Jan 28 '26 01:01

ak_tyagi


1 Answers

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)")
    }
}
like image 118
Starsky Avatar answered Jan 29 '26 14:01

Starsky