Injecting JavaScript into UIWebView

3.2k views Asked by At

I am trying to use the stringByEvaluatingJavaScriptFromString: to alter a WebView and it's not executing as I expect.

Here is the code, this JS doesn't execute though. Any idea why?

UIWebView *wv = [UIWebView alloc] init];

NSURL *url = [[NSURL alloc] initWithString:@"http://www.google.com"];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

[wv loadRequest:request];

[wv stringByEvaluatingJavaScriptFromString:@"document.write('This Works')"];
1

There are 1 answers

5
phi On BEST ANSWER

Probably you'll have to wait for the request to finish before you can use stringByEvaluatingJavaScriptFromString. Set wv.delegate = self; and then implement -webViewDidFinishLoad like this

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    [webView stringByEvaluatingJavaScriptFromString:@"document.write('This Works')"];
}