Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating input text field in WKWebView

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.

like image 962
mm24 Avatar asked Apr 10 '15 12:04

mm24


2 Answers

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.

like image 64
badger_cl Avatar answered Nov 18 '22 08:11

badger_cl


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 -

enter image description here

like image 25
Uttam Sinha Avatar answered Nov 18 '22 08:11

Uttam Sinha