SWIFT: Filling HTML input [type=“text”]

2019-08-01 03:24发布

How to fill fields on an HTML form that is currently being presented in a web view? The purpose of this application is meant to auto log-in into a website. On basis of different tutorials I mostly copy-pasted a swift code but mine does not work. It would be great to get a hint what the mistake could be or even a complete different approach is very much appreciated.

The important parts of the website I want to login is built like this:

text-field Username:

<input type="text" class="form-control" name="username" id="username" placeholder="Username:">

text-field Password:

<input type="password" class="form-control" name="password" id="password" maxlength="20" placeholder="Passwort:">

LogIn-Button (to submit the login):

<input type="submit" value="login" class="btn btn-default">

My broken swift-code of the ViewController.swift:

It just loads the website but without filling in the username or password and without submitting.

@IBOutlet weak var MyWebView: UIWebView!

func webViewDidFinishLoad(MyWebView: UIWebView) {

    // fill data
    let savedUsername = "USERNAME"
    let savedPassword = "PASSWORD"

    let fillForm = String(format: "document.getElementById('username').value = '\(savedUsername)';document.getElementById('password').value = '\(savedPassword)';")
    MyWebView.stringByEvaluatingJavaScript(from: fillForm)

    //submit form
    let deadlineTime = DispatchTime.now() + .seconds(1)
    DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
        MyWebView.stringByEvaluatingJavaScript(from: "document.value[\"login\"].submit();")
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL (string: "https://www.austrocontrol.at/flugwetter/")
    MyWebView.loadRequest(URLRequest(url: url!))
    webViewDidFinishLoad(MyWebView: MyWebView)
}

I am not sure how to deal with this output I got from the Xcode-simulator but maybe it helps in a way:

[...] Starting WebFilter logging for process AustroControl Viewer
[...] _userSettingsForUser : (null)
[...] _WebFilterIsActive returning: NO
[...] [MediaRemote] [AVOutputContext] WARNING: AVF context unavailable for +[MRAVOutputContext sharedAudioPresentationContext]_block_invoke
[...] [MediaRemote] [AVOutputContext] WARNING: AVF context unavailable for +[MRAVOutputContext createOutputContextWithUniqueIdentifier:]

1条回答
Deceive 欺骗
2楼-- · 2019-08-01 03:43

First of all: it's better to use WKWebView.

You can make a function that runs JavaScript in your WebView and fills the HTML form just before submitting it.

private func setWebViewValue(name: String, data: String) {
    let jsFunc = "document.getElementById(\"\(name)\").value = \"\(data)\""
    webView.evaluateJavaScript(jsFunc, completionHandler: nil)
}
查看更多
登录 后发表回答