cdietschrun
cdietschrun

Reputation: 1683

putting javascript into uiwebview problems

I'm trying to run the following code in my webViewDidFinishLoading:

NSString* len = [self.webView stringByEvaluatingJavaScriptFromString:@"document.links.length"];
    NSInteger lenVal = [len intValue];
    for( int i=0; i<lenVal; ++i ) {

        NSString *value = [[NSNumber numberWithInt: i] stringValue];
        NSString *link = @"document.links[";
        link = [link stringByAppendingString:value];
        link = [link stringByAppendingString:@"]"];
        NSString* links = [self.webView stringByEvaluatingJavaScriptFromString:link ];
        NSLog(@"val: %@", links);
    }

The idea is that I have a webview that is loaded, the page I am on I want to then get all the links displayed on the page. Opening a console in chrome an typing document.links gives 83 (# of links) and document.links[0] though [82] display just what I want. But when I run this code (and a bunch of other attempts), I can't seem to get links to have any value (always seems to return empty).

Can anyone please help?

Upvotes: 0

Views: 344

Answers (1)

Jim Blackler
Jim Blackler

Reputation: 23169

You're on the right track, but you can't return a JavaScript object with stringByEvaluatingJavaScriptFromString without first converting it to a string, typically with .toString() of JSON.stringify(..) (although the latter won't work for DOM objects).

Try changing line 8 to

link = [link stringByAppendingString:@"].toString()"];

and see what happens.

Upvotes: 2

Related Questions