如何在UIWebView加载请求之前设置sessionStorage?

时间:2017-08-04 08:19:44

标签: javascript swift uiwebview sessionstorage

代码

以下是我一直在尝试做的事情:

import UIKit
import WebKit

class WebViewViewController: UIViewController {
    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSURL(string: "http://example.com/index.html")
        webView.stringByEvaluatingJavaScript(from: "sessionStorage.setItem('exampleKey','exampleValue');")
        let request = URLRequest(url: url! as URL)
        webView.loadRequest(request)
    }
}

问题

但是,在Safari中查找模拟器会话控制台时,存储不包含exampleKey

问题

如何在加载http://example.com/index.html之前设置sessionStorage?

修改

Alexandre Lara提出的解决方案对我不起作用。

import UIKit
import WebKit

class WebViewViewController: UIViewController, UIWebViewDelegate {
    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSURL(string: "http://example.com/index.html")
        let request = URLRequest(url: url! as URL)
        webView.delegate = self
        webView.loadRequest(request)
    }

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        webView.stringByEvaluatingJavaScript(from: "sessionStorage.setItem('exampleKey','exampleValue');")
        return true
    }
}

1 个答案:

答案 0 :(得分:0)

您可以通过webView(_:shouldStartLoadWith:navigationType:)实施UIWebViewDelegate来解决这个问题:

class WebViewViewController: UIViewController, UIWebViewDelegate {
    // ...
    let url = NSURL(string: "http://example.com/index.html")
    let request = URLRequest(url: url! as URL)
    webView.loadRequest(request)
    // ...

    // Set delegate and implement the method
    webView.delegate = self

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) {
        webView.stringByEvaluatingJavaScript(from: "sessionStorage.setItem('exampleKey','exampleValue');")
    }
}