Populating Input Text Field in Wkwebview

How to pre-fill a text box on a website in a WKWebView using swift

Recommend you can use like this ,

//   let source = "document.body.style.background = \"#777\";"

let source = "document.getElementById('q').value = 'Hello' ;"
let userScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)

let userContentController = WKUserContentController()
userContentController.addUserScript(userScript)

let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
webView = WKWebView(frame: self.view.bounds, configuration: configuration)
view.addSubview(webView)
let url = URL (string: "https://www.google.com")
let request = URLRequest(url: url!)
webView.load(request)

as Apple said , A WKUserContentController object provides a way for JavaScript to post messages and inject user scripts to a web view.

Pre-fill WebView text fields

I had obtained the element IDs by highlighting them in Firefox and selecting inspect element.
Turns out this gives different IDs to those returned with:

NSString *body = [self.emailWebView stringByEvaluatingJavaScriptFromString:
@"document.getElementsByTagName('body')[0].outerHTML"];
NSLog(@"%@", body);

Plugging these IDs (which apparently vary dependent upon what was used to navigate to the page) into:

[self.emailWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('username').value = '%@';", user]];
[self.emailWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('password').value = '%@';", pw]];
[self.emailWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('input_LoginPage-ipad_1').click();"]];

Solved it.

Thanks for all your help folks.

Set text for a textfield in UIWebView

Yes you can set the text for a textfield in the UIWebView using javascript

As an example if you have a textfield in this form

<input id="textFieldID" type="text" value="TextValue"/>

Setting value:

[theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('textFieldID').value = 'Hello World'"]

Getting value:

NSString* value = [theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('textFieldID').value"];


Related Topics



Leave a reply



Submit