Is there a way to set local storage in WKWebView

2019-04-28 15:33发布

问题:

I want to set local storage before making request to WKWebView is that possible in any iOS version?

Can't find a way to do it, the only class seem to relevant is WKWebsiteDataStore https://developer.apple.com/documentation/webkit/wkwebsitedatastore which only have method to read and delete.

回答1:

From @paulvs comment here is what I do.

Set navigation delegate to listen to finished callback.

webView.navigationDelegate = self

Then in the callback, check for value in localStorage and set if needed.

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    webView.evaluateJavaScript("localStorage.getItem(\"key\")") { (result, error) in

        // check if result is what I want
        // if it is what I want, do nothing
        // if not set it
        webView.evaluateJavaScript("localStorage.setItem(\"key\", \"value\")") { (result, error) in

            webView.reload()

        }            
    }
}