nidIOS
nidIOS

Reputation: 167

Access WebView Elements in objective C

Anybody please help me, how can i get all the textFields values (with their "name" "id") inside a loaded UIWebView page.

or please provide a link which describes all jQuery String to pass in

               "stringByEvaluatingJavaScriptFromString"

method as a parameter.

Upvotes: 1

Views: 685

Answers (2)

HMHero
HMHero

Reputation: 2343

This tutorial might help.

How to parse html on ios: http://www.raywenderlich.com/14172/how-to-parse-html-on-ios

Upvotes: 0

smnh
smnh

Reputation: 1745

Here is the JavaScript code you should use:

(function(){
    var i, tf, textFields = document.getElementsByTagName("input"), result = [];
    for (i = 0; tf = textFields[i]; i++) {
        if (tf.type === "text" || tf.type === "search")
            result.push({
                "type": tf.type,
                "name": tf.name,
                "id": tf.id,
                "value": tf.value
            });
    }
    return JSON.stringify(result);
})();

You may find that you want to add additional input field types.

Here is an Objective-C code example:

- (void)getValuesButtonTapped:(id)sender {
    NSString *resultStr = [self.webView stringByEvaluatingJavaScriptFromString:
        @"(function(){"
            "var i, tf, textFields = document.getElementsByTagName(\"input\"), result = [];"
            "for (i = 0; tf = textFields[i]; i++) {"
                "if (tf.type === \"text\" || tf.type === \"search\")"
                    "result.push({\"type\": tf.type, \"name\": tf.name, \"id\": tf.id, \"value\": tf.value});"
            "}"
            "return JSON.stringify(result);"
        "})();"
    ];
    NSArray *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    NSLog(@"result: %@", result);
}

enter image description here

When you tap the "get values ..." button you get the following log message:

result: ({
    id = "lst-ib";
    name = q;
    type = search;
    value = "hello world";
},
    {
    id = "";
    name = "";
    type = text;
    value = "";
},
    {
    id = "";
    name = "";
    type = text;
    value = "";
})

Upvotes: 1

Related Questions