0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent thank you it worked! I'm very shaky/new with javascript and would not have known that. As an aside, do you have any idea why my webViewdidfinishLoad appears to be called multiple times when loading my URL? It seems possibly due to ads loading? It fires approximately 4 or 5 times for me.
No problem. webViewdidfinishLoad is called for every different file downloaded on the page, which could include css, scripts, images or other files. Logging the URL queried with NSLog will show you what they are in your case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.