Monday, June 3, 2013

UIWebView stringByEvaluatingJavaScriptFromString example in Objective C (iOS).


UIWebView stringByEvaluatingJavaScriptFromString

Returns the result of running a script.

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script

Parameters
script
The script to run.

Return Value
The result of running script or nil if it fails.

Discussion of [UIWebView stringByEvaluatingJavaScriptFromString]
JavaScript execution time is limited to 10 seconds for each top-level entry point. If your script executes for more than 10 seconds, the web view stops executing the script. This is likely to occur at a random place in your code, so unintended consequences may result. This limit is imposed because JavaScript execution may cause the main thread to block, so when scripts are running, the user is not able to interact with the webpage.[UIWebView stringByEvaluatingJavaScriptFromString]

JavaScript allocations are also limited to 10 MB. The web view raises an exception if you exceed this limit on the total memory allocation for JavaScript.

UIWebView stringByEvaluatingJavaScriptFromString example.
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
   [googleRequestResponseData appendData:data];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
   [web_screen loadData:googleRequestResponseData MIMEType:@"application/octet-stream" textEncodingName:@"utf-8" baseURL:googleURL];
   NSString *js_result = [web_screen stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('input')[1].value='test';"];
   NSLog (js_result);

   [googleURL release];
   [googleRequestResponseData release];
   [connectionInProgress release];
   connectionInProgress = nil;
}

Example of [UIWebView stringByEvaluatingJavaScriptFromString].
UIWebView *wv = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, 700.0, 700.0)];
[self.view addSubview:wv];
wv.delegate = self;
[wv loadHTMLString:@"<html><head><script type='text/javascript'>function sample() {alert('Paznja');}</script></head><body><h1>TEST</h1></body></html>" baseURL:nil];
[wv release];
and in the same class:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
   [webView stringByEvaluatingJavaScriptFromString:@"sample()"];
}

UIWebView stringByEvaluatingJavaScriptFromString example.
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
[self.view addSubview:webView];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:
                    @"function f(){ return \"hello\"; } f();"];
NSLog(@"result: '%@'", result); // 'hello'
[webView release];

End of UIWebView stringByEvaluatingJavaScriptFromString example article.