View Controller
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.
}
}
测试.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
:
所以我的问题:
在 UIWebView
加载其初始请求之前设置本地存储的正确方法是什么?
编辑:
感谢 @Wez 指出我应该在 webViewDidFinishLoad
中评估 JavaScript,但我想要做的是在加载该页面之前设置 localStorage(我们将在其初始请求中使用该 localStorage)。所以我无法在 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")))
关于ios - 如何在 UIWebView 加载其初始请求之前设置本地存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42622192/