Question

I have a UIWebview that automatically fills in the username and password of the user. Now, all I need is for the webview to automatically submit as if the user had pressed the Sign in button. Is there anyway to call this function programmatically to a webview? By the way, I am using hotmail as the website if this helps at all.

Was it helpful?

Solution

To cause the form to be submitted, what you need to do is execute a piece of javascript code that finds the DOM element of the submit button, and then calls the click() method on that.

I don't know anything about the structure of the hotmail login page, but if there's an id attribute on the submit button, you can use document.getElementById(...) to retrieve it. Otherwise you may have to write code to look through all the input elements to find one with type="submit".

In the simple case, let's suppose the submit button has an id of "submit_button". Then in your Objective C code you would have the following:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *code = @"document.getElementById('submit_button').click()";
    [webView stringByEvaluatingJavaScriptFromString: code]
}

If you need to do anything more complex, you can change the content of the code string. This is simply javascript code that gets run in the context of the page.

Stepping back for a moment though, I'd recommend you think about a more reliable way to do this. Hotmail's login page could change at any time, and your app will break if they alter the way that the submit button works, e.g. giving it a different name, or using some other means of detecting input (such as an javascript onclick handler). In general, relying on a specific HTML structure of a site in your app is likely to cause problems - if you can, you're better off using a web service (e.g. REST) style API, if one is provided.

OTHER TIPS

The web content that gets loaded in the web view should include the javascript to submit the page. Implement webViewDidFinishLoad: in your WebViewController & call stringByEvaluatingJavaScriptFromString:@"yourJavascriptSubmitMethodCall()" I am away from mac/xcode. Worth trying.

You can search the webview for submit buttons, then click on the first. It should work in a lot of cases.

- (void)clickOnSubmitButtonForWebView:(UIWebView *)webView {

    NSString *performSubmitJS = @"var passFields = document.querySelectorAll(\"input[type='submit']\"); \
    passFields[0].click()";
    [webView stringByEvaluatingJavaScriptFromString:performSubmitJS];

}

Web view is not mean to call functions for you. It will just help you to show your page contents in a specified format. Log in or any other such functionality should be handled programatically at the back end of your web site code. That's what I can say on this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top