fill form in webview in swift

Assuming that you have added a UIWebView in your view controller and loaded a web page with a form in it, you can fill the form programmatically using the following steps:

  1. Get a reference to the web view object:
main.swift
let webView = UIWebView()
26 chars
2 lines
  1. Get a reference to the form element in the HTML page. You can do this using the stringByEvaluatingJavaScript(from:) function of the web view object:
main.swift
let form = "document.forms[0]"
31 chars
2 lines
  1. To set a value for an input field in the form, you can use the value property of the input element. You need to provide the name of the form input and the value that you want to set:
main.swift
let username = "\(form).username.value = 'John'"
49 chars
2 lines
  1. Call the stringByEvaluatingJavaScript(from:) function of the web view object with the JavaScript code to set the form data:
main.swift
webView.stringByEvaluatingJavaScript(from: username)
53 chars
2 lines
  1. You can repeat the above steps to set the values for other inputs in the form.

With the above steps, you should be able to fill the form inside the web view programmatically.

related categories

gistlibby LogSnag