有没有办法在WKWebView中设置本地存储

sar*_*unw 6 local-storage ios wkwebview

我想在提出请求之前设置本地存储WKWebView是否可以在任何iOS版本中使用?

找不到办法做到这一点,唯一看来相关的类是WKWebsiteDataStore https://developer.apple.com/documentation/webkit/wkwebsitedatastore,它只有读取和删除的方法.

sar*_*unw 10

来自@paulvs评论这里就是我做的.

设置导航委托以侦听已完成的回调.

webView.navigationDelegate = self

然后在回调中,检查localStorage中的值并根据需要进行设置.

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

        }            
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个工作在`WKWebView`加载一次之后,对吗?如果,我想在`viewDidLoad`上发出第一个请求之前设置本地存储项怎么办? (6认同)
  • Koshub 的答案(/sf/answers/4443955701/)应该是公认的答案,它比重新加载 webview 更优雅。 (2认同)

小智 7

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]) ?? [:]
}
Run Code Online (Sandbox Code Playgroud)