本文介绍了如何在加载 URLRequest 之前在 webView 中设置 localStorage 项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to access a web page that has token on its 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)

推荐答案

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

the main problem was that you can't run javascript script that add localStorage item before the web view load so i had to wait utile that page is loaded then then run javascript script that add needed token then reload that page Here is my code but again it's bad practice i think and i believe that front end team should allow me to end that token in request headerfist there was that method with reload the web view only one time

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

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

then i had to confirm to WKNavigationDelegate delegate to reload that page when it's loaded and here is my code

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

    }
}

这篇关于如何在加载 URLRequest 之前在 webView 中设置 localStorage 项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 09:17