gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:15:20 24 4
gpt4 key购买 nike

代码

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

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 中查找模拟器的控制台时,sessionStorage 不包含 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
}
}

最佳答案

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

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');")
}
}

关于javascript - 如何在 UIWebView 加载请求之前设置 sessionStorage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45501677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com