问题
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?
回答1:
In case you're looking for a Swift version:
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")))
回答2:
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
var configuration = new WKWebViewConfiguration();
var contentController = new WKUserContentController();
string js = "javascript: localStorage.setItem('key', 'value')";
var userScript = new WKUserScript((NSString)js, WKUserScriptInjectionTime.AtDocumentStart, false);
contentController.AddUserScript(userScript);
configuration.UserContentController = contentController;
WKWebView _wKWebView = new WKWebView(this.View.Frame,configuration);
var url = "Your Url";
var webViewRequest = new NSMutableUrlRequest(new Foundation.NSUrl(url));
_wKWebView.LoadRequest(webViewRequest);
回答3:
Localhost doesn't work try this one:
wv.loadRequest(URLRequest(url: URL(string: "http://10.0.2.2:63343/test.html")!))
来源:https://stackoverflow.com/questions/42622192/how-to-set-the-local-storage-before-a-uiwebview-loading-its-initial-request