WKWebView removes automatically filled in data

Viewed 199

I try to automatically fill in a login formula and confirm data by clicking the login button. I would like to use Swift 5, macOS 10.15 and a WKWebView.

The first step is done, I can fill in my login data like this:

import Cocoa
import WebKit

class ViewController: NSViewController, WKUIDelegate, WKNavigationDelegate {
    let webView = WKWebView()
    let button = NSButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        button.frame = CGRect(x: 400, y: 0, width: 40, height: 20)
        button.image = NSImage(named: NSImage.Name("Button"))
        button.target = self
        button.action = #selector(self.fillIn)
        self.view.addSubview(button)

        self.webView.uiDelegate = self
        self.webView.navigationDelegate = self
        webView.frame = CGRect(x: 0, y: 0, width: 400, height: 270)
        view.addSubview(webView)
        let url = URL(string: "https://lobby.ogame.gameforge.com/de_DE/hub")
        let request = URLRequest(url: url!)
        webView.load(request)
    }

    @objc func fillIn() {
        setWebViewValue(name: "email", data: "user@web.de")
        setWebViewValue(name: "password", data: "pwdpwd")
    }

    func setWebViewValue(name: String, data: String) {
        let jsFunc = "document.getElementsByName(\"\(name)\")[0].value = \"\(data)\""
        webView.evaluateJavaScript(jsFunc) {(result, error) in
            print(result, error)
        }
    }
}

But when I click the login button, all data will be removed. So the email and password input fields are empty while logging in and I get an invalid input data error.

Example

Example gif

Please note, even if the email address is wrong, the address and password input fields are not cleared when clicking to the login button.

Question:

Why is the auto-filled data deleted when you click the login button and why is the data that was entered normally not deleted?

1 Answers

Check the javascript code on the page to see if it is clearing the fields on it's own or maybe it was waiting for typing into the fields.

Related