Having an HTML form embedded in a WKWebView in my Swift app poses a problem when trying to extract the textbox content using a message handler. The issue arises when pressing the Register button, which triggers a JavaScript function to retrieve the values of the textboxes. Strangely, the first result is empty, just a space character.
Upon pressing the button again, the actual content of the textboxes is successfully obtained. I've experimented with using the evaluateJavascript function to target elements by ID, but encountered the same behavior – blank response on the first attempt, followed by the expected values on subsequent tries.
The code snippet from my ViewController:
private var webkitview: WKWebView!
var lsusername = "";
var lspassword = "";
@IBOutlet weak var baseview: UIView!
@IBOutlet weak var registerAccountButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.webkitview = WKWebView(frame: self.baseview.bounds, configuration: self.getWKWebViewConfiguration())
baseview.addSubview(self.appvalleyRegistration)
baseview.translatesAutoresizingMaskIntoConstraints = false;
let url = URL(string: "https://redacted.com/registrationform.php")!
webkitview.load(URLRequest(url: url))
}
//Remaining view controller code...
When triggering the showUser()
alert method, it displays nothing initially, only revealing the correct username and password fetched via WebKit after the second button press.
Excerpt from my form's script:
<body>
<script type="text/javascript">
function submitForm() {
var message = {
passw: document.getElementById("passw").value,
email: document.getElementById("email").value
};
window.webkit.messageHandlers.observer.postMessage(message);
}
</script>>
<div class="container">
<h1>Welcome to my site</h1>
<p>Let's set up your account</p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" id="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="passw" id="passw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" id="psw-repeat" required>
</div>
</body>
Unable to comprehend why functionality behaves inconsistently between first and subsequent attempts, I even tried introducing a sleep()
delay to no avail.