wkwebview auto fill login form swift 2

2019-06-25 17:21发布

im new in the Swift World. I have a big problem ... I've tried to write an app that has only one WKWebView. It is like a web browser. The app should be able to fill die LogIn Fields automatically from an object or a list. But for test reasons i have put the login data into variables.

class ViewController: UIViewController , WKNavigationDelegate{

// Zugänge
let pw : String = "test"
let bn : String = "test@test.com"
// Adresse
let adresse : String = "https://www.facebook.com"

var webView: WKWebView!

func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
    title = webView.title
}
override func loadView() {
    webView = WKWebView()
    webView.navigationDelegate = self
    view = webView
}


override func viewDidLoad() {
    super.viewDidLoad()
    let url = NSURL(string: adresse)!
    webView.loadRequest(NSURLRequest(URL: url))
    webView.allowsBackForwardNavigationGestures = true

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

i think this is possible with JS but i don't know how.

Is there any way so solve my Problem?

1条回答
疯言疯语
2楼-- · 2019-06-25 17:32

This is actually doable using 1Password

Add the extension files:

  • OnePasswordExtension.h
  • OnePasswordExtension.m

Then include them using a bridging header:

#import "OnePasswordExtension.h"

Finally, you can use the following in your project

@IBAction func onePassword_btn(sender: AnyObject) {
OnePasswordExtension.sharedExtension().fillLoginIntoWebView(self.webView, forViewController: self, sender: sender, completion: {(Bool) in
// error handling
})
}

Here is the link to the 1Password

Here is the reference

or you can simply try like this

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)
    }
}
查看更多
登录 后发表回答