ViewController
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>
I called localStorage.setItem('key', 'value')
before loadRequest
. I expect that alert will output value
, but it outputed null
:
So my question:
What's the correct way to set the local storage before a UIWebView
loading its initial request?
EDIT:
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...
Is there any way to achieve that?
You can use WKWebView instead UIWebView and load the script. take a look in this sample, I created in C# but you can translate it to Objetive-c/Swift
Localhost doesn't work try this one:
In case you're looking for a Swift version: