Autofill Username and Password UIWebView Swift

后端 未结 1 457
無奈伤痛
無奈伤痛 2021-01-03 08:38

I\'ve found many ways to autofill a username and password in objective-c, but I can\'t figure out how to make it work with Swift. What would be the Swift equivalent of this

相关标签:
1条回答
  • 2021-01-03 09:26

    Here is a simple swift conversion of your provided code. SStringByEvaluatingJavaScriptFromString has been tested using different javascript and works correctly.

    func webViewDidFinishLoad(webView: UIWebView!) {
    
        let savedUsername = NSUserDefaults.standardUserDefaults().stringForKey("USERNAME")
        let savedPassword = NSUserDefaults.standardUserDefaults().stringForKey("PASSWORD")
    
        if savedUsername == nil || savedPassword == nil {return}
    
        if ( countElements(savedUsername!) != 0 && countElements(savedPassword!) != 0) {
            let loadUsernameJS = "var inputFields = document.querySelectorAll(\"input[name='username']\"); \\ for (var i = inputFields.length >>> 0; i--;) { inputFields[i].value = \'\(savedUsername)\';}"
            let loadPasswordJS = "var inputFields = document.querySelectorAll(\"input[name='password']\"); \\ for (var i = inputFields.length >>> 0; i--;) { inputFields[i].value = \'\(savedPassword)\';}"
    
            self.webview.stringByEvaluatingJavaScriptFromString(loadUsernameJS)
            self.webview.stringByEvaluatingJavaScriptFromString(loadPasswordJS)
        }
    }
    
    0 讨论(0)
提交回复
热议问题