xcode 如何在Swift 3中访问输入到WKWebView中的用户名和密码

cx6n0qe3  于 2022-11-18  发布在  Swift
关注(0)|答案(1)|浏览(145)

我正在Swift 3中尝试使用WKWebView构建一个iOS应用程序。WebView从其URL加载网站。我需要能够访问用户输入WebView的用户名和密码,以便在用户单击提交按钮时将其保存到UserDefaults。有办法做到这一点吗?谢谢!!

ui7jx7zq

ui7jx7zq1#

xcode 12.4中的函数

extension ViewController: WKNavigationDelegate{

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        

        let lurl:String = webView.url?.absoluteString ?? ""
        
        if (lurl.contains(pagweb+"index.php")) { 
            let defaults = UserDefaults.standard
            var user:String = ""
            var pass:String = ""
            var rememberme: Bool = false
            
            wv.evaluateJavaScript("document.getElementById('user').value;") { (res, error) in
                if res != nil {
                    user = res as! String
                }
            }
            wv.evaluateJavaScript("document.getElementById('pass').value;"){ (res, error) in
                if res != nil {
                    pass = res as! String
                }
            }
            wv.evaluateJavaScript("document.getElementById('rememberme').checked;"){ (res, error) in
                if res != nil {
                    rememberme = res as! Bool
                    if rememberme {
                        defaults.set(user, forKey: "USERNAME")
                        defaults.set(pass, forKey: "PASSWORD")
                        defaults.set(true, forKey: "rememberme")
                    }else if pass.count > 7 && user.count > 0{
                        defaults.set("", forKey: "USERNAME")
                        defaults.set("", forKey: "PASSWORD")
                        defaults.set(false, forKey: "rememberme")
                    }
                }
            }
            
        }
    }


func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        // user - pass - rememberme
        let savedUsername = UserDefaults.standard.string(forKey: "USERNAME")
        let savedPassword = UserDefaults.standard.string(forKey: "PASSWORD")
        let savedrememberme = UserDefaults.standard.bool(forKey: "rememberme")
        
        if savedrememberme {
            wv.evaluateJavaScript("document.getElementById('user').value = '"+savedUsername!+"';")
            wv.evaluateJavaScript("document.getElementById('pass').value = '"+savedPassword!+"';")
            wv.evaluateJavaScript("document.getElementById('rememberme').checked = true;")
        }else{
            wv.evaluateJavaScript("document.getElementById('user').value = '';")
            wv.evaluateJavaScript("document.getElementById('pass').value = '';")
            wv.evaluateJavaScript("document.getElementById('rememberme').checked = false;")
        }
    }

}

相关问题