Calling Javascript using UIWebView

learner2010 picture learner2010 · Jan 16, 2012 · Viewed 63.8k times · Source

I am trying to call a javascript in a html page using the function -

View did load function
{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"BasicGraph.html"];
    NSURL *urlStr = [NSURL fileURLWithPath:writablePath];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"BasicGraph" ofType:@"html"];
    [fileManager copyItemAtPath:myPathInfo toPath:writablePath error:NULL];

    [graphView loadRequest:[NSURLRequest requestWithURL:urlStr]];
}

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

Here is the javascript on the html page -

<script>
    function methodName()
      {
         // code to draw graph
      }

However, the function methodName() is not getting called but after window.onload = function () everything is working fine..

I am trying to integrate RGraphs into my application and Basic.html is the html page in which the javascripts are written.

It would be great if someone could help me out with this.

Answer

Bj&#246;rn Kaiser picture Björn Kaiser · Jan 16, 2012

Simple: You try to execute the JS function from Objective-C before the page even has been loaded.

Implement the UIWebView's delegate method webViewDidFinishLoad: in your UIViewController and in there you call [graphView stringByEvaluatingJavaScriptFromString:@"methodName()"]; to make sure the function gets called after the page has been loaded.