I have loaded the following html page in a WKWebView controlled by a specific view controller. After the view is loaded I would like that the App automatically populates an input text field in the page.
In this example I would like the app to write "Hello Result" in the "Result" text field of the form below.
<html>
<head>
<title>Test Page</title>
</head>
<body>
<form>
QR Result <input type="text" name="Result" width="20">
</form>
</body>
</html>
This is the code where I load the HTML page as file within the view controller:
var htmlFile = NSBundle.mainBundle().pathForResource("apptest", ofType: "html")
var contents = NSString(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding, error: nil)
self.webView?.loadHTMLString(contents!, baseURL: nil)
It doesn't matter how I load the view (file or URL). What I want to be able to do is to fill the field at some point after loading the view.
The wkwebview/swift equivalent for Uttam Sinha's answer would be.
webview.evaluateJavaScript("document.getElementById('result').value = 'Hello Result';", completionHandler: { (res, error) -> Void in
//Here you can check for results if needed (res) or whether the execution was successful (error)
})
The WKWebView's version is nicer since it will provide error feedback in case of problems executing your JS.
I have added id attribute in textfield -
<form>
QR Result <input type="text" id="result" name="Result" width="20"/>
</form>
In Swift -
func webViewDidFinishLoad(webView: UIWebView!) {
self.wbView.stringByEvaluatingJavaScriptFromString("document.getElementById('result').value = 'Hello Result';")
}
Check screenshot -
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With