How to set the local storage before a UIWebView lo

2019-07-17 06:09发布

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:

enter image description here

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?

3条回答
时光不老,我们不散
2楼-- · 2019-07-17 06:29

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楼-- · 2019-07-17 06:29

Localhost doesn't work try this one:

wv.loadRequest(URLRequest(url: URL(string: "http://10.0.2.2:63343/test.html")!))
查看更多
别忘想泡老子
4楼-- · 2019-07-17 06:47

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)

let webview = WKWebView(configuration: configuration)
webview.load(URLRequest(url: URL(string: "your URL")))
查看更多
登录 后发表回答