Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set local storage in WKWebView

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.

like image 836
sarunw Avatar asked Jul 04 '17 04:07

sarunw


2 Answers

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()

        }            
    }
}
like image 131
sarunw Avatar answered Oct 21 '22 23:10

sarunw


You do not need to reload the page - just inject the local storage data using WKUserScript at .atDocumentStart

// Restore local storage

// Instantiate the configuration before instantiating `WKWebView`

let configuration = WKWebViewConfiguration()

// Clear existed local storage just after document element is created

let script = WKUserScript(
    source: "window.localStorage.clear();",
    injectionTime: .atDocumentStart,
    forMainFrameOnly: true
)
configuration.userContentController.addUserScript(script)

// Preare your local storage data

let localStorageData: [AnyHashable : Any] = [:]

if JSONSerialization.isValidJSONObject(localStorageData),
    let data = try? JSONSerialization.data(withJSONObject: localStorageData, options: []),
    let value = String(data: data, encoding: .utf8) {
    // Inject valid local storage data just after document element is created
    let script = WKUserScript(
        source: "Object.assign(window.localStorage, \(value));",
        injectionTime: .atDocumentStart,
        forMainFrameOnly: true
    )
    configuration.userContentController.addUserScript(script)
}

// Instantiate WebView with the configuration

let webView = WKWebView(frame: .zero, configuration: configuration)
        
// Later you may save the updated local storage
webView.evaluateJavaScript("Object.assign({}, window.localStorage);") { (result, error) in
    // let updatedlocalStorageData = (result as? [AnyHashable : Any]) ?? [:]
}
like image 7
Koshub Avatar answered Oct 21 '22 22:10

Koshub