如何在加载 URLRequest 之前在 webView 中设置 localStorage 项?

How to set localStorage item in webView before loading a URLRequest?

我必须访问一个在其 localStorage 上有令牌的网页

let javascript = "localStorage.setItem('token', 'abc')"
let url = URL(string: "https://test.com/abc")
webView.evaluateJavaScript(javascript) { (_, err) in
        print(err?.localizedDescription)
        // This will return 'A JavaScript exception occurred'
    }
let request = URLRequest(url: url!)
webView.load(request)

我认为这是不可能的。您收到此错误:

Error Domain=WKErrorDomain Code=4 
"A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=0, 
WKJavaScriptExceptionMessage=SecurityError: The operation is 
insecure., WKJavaScriptExceptionColumnNumber=0, 
NSLocalizedDescription=A JavaScript exception occurred}

对于 WKWebView,您无能为力。

i solve it but i think it's a bad practice and the right way was to be able to send token in request's header

主要问题是您不能 运行 javascript 在 Web 视图加载之前添加 localStorage 项目的脚本,所以我不得不等待 utile 页面加载然后 运行 javascript 添加所需令牌然后重新加载该页面的脚本这是我的代码,但我认为这是不好的做法,我相信前端团队应该允许我在请求中结束该令牌 header 第一种方法是只重新加载 web 视图一次

var loaded = false
func load() {
    if !loaded {
        webView.reload()
    }
    loaded = true
}

然后我必须确认 WKNavigationDelegate 委托在加载该页面时重新加载该页面,这是我的代码

extension ViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript(javascript) { (_, err) in
            self.load()
        }

    }
}