如何在UIWebView加载初始请求之前设置本地存储? [英] How to set the local storage before a UIWebView loading its initial request?
问题描述
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let wv = UIWebView(frame: UIScreen.main.bounds)
wv.stringByEvaluatingJavaScript(from: "localStorage.setItem('key', 'value')")
wv.loadRequest(URLRequest(url: URL(string: "http://localhost:63343/test.html")!))
self.view.addSubview(wv)
// Do any additional setup after loading the view, typically from a nib.
}
}
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
alert(localStorage.getItem("key"))
</script>
</head>
<body>
</body>
</html>
我在loadRequest
之前叫localStorage.setItem('key', 'value')
.我希望警报将输出value
,但输出null
:
I called localStorage.setItem('key', 'value')
before loadRequest
. I expect that alert will output value
, but it outputed null
:
所以我的问题:
在UIWebView
加载初始请求之前设置本地存储的正确方法是什么?
What's the correct way to set the local storage before a UIWebView
loading its initial request?
感谢@Wez指出我应该在webViewDidFinishLoad
中评估JavaScript,但是我想做的是在加载该页面之前设置localStorage(我们将在其初始请求中使用该localStorage).所以我无法在webViewDidFinishLoad中对其进行评估...
Thank @Wez for pointing out I should evaluate JavaScript in webViewDidFinishLoad
, but What I want to do is setting that localStorage before that page loaded(we will use that localStorage in its initial request). So I can't evaluate it in webViewDidFinishLoad...
有什么方法可以实现?
推荐答案
如果您正在寻找 Swift 版本:
let configuration = WKWebViewConfiguration()
let contentController = WKUserContentController()
let js = "javascript: localStorage.setItem('key', 'value')"
let userScript = WKUserScript(source: js, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
contentController.addUserScript(userScript)
configuration.userContentController = contentController
let webview = WKWebView(configuration: configuration)
webview.load(URLRequest(url: URL(string: "your URL")))
这篇关于如何在UIWebView加载初始请求之前设置本地存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!