如何在UIWebView加载其初始请求之前设置本地存储?

时间:2017-03-06 09:42:05

标签: ios swift webview uiwebview

的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>

我在localStorage.setItem('key', 'value')之前致电loadRequest。我希望该提醒会输出value,但会超出null

enter image description here

所以我的问题:

UIWebView加载初始请求之前设置本地存储的正确方法是什么?

编辑:

感谢@Wez指出我应该在webViewDidFinishLoad中评估JavaScript,但我想要做的是在加载该页面之前设置localStorage(我们将在其初始请求中使用该localStorage)。所以我无法在webViewDidFinishLoad评估它...

有没有办法实现这个目标?

3 个答案:

答案 0 :(得分:1)

您可以使用WKWebView代替UIWebView并加载脚本。看一下这个样本,我是用C#创建的,但你可以把它翻译成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);

答案 1 :(得分:1)

如果您正在寻找 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)

let webview = WKWebView(configuration: configuration)
webview.load(URLRequest(url: URL(string: "your URL")))

答案 2 :(得分:0)

Localhost不起作用试试这个:

wv.loadRequest(URLRequest(url: URL(string: "http://10.0.2.2:63343/test.html")!))