Timo Ernst
Timo Ernst

Reputation: 15973

How do I call a JavaScript function from within Objective-C in a Phonegap app for iPhone?

I created a Phonegap app for iPhone which works well so far.

Now I need to call a JavaScript function from within my Objective-C code.

How do I do this? I already tried the following but it won't work:

In AppDelegate.m method "didFinishLaunchingWithOptions":

[self.viewController.webView stringByEvaluatingJavaScriptFromString:@"test()"];

In my JavaScript file:

function test(){
    alert("called");
}

Result: Nothing happens. What's wrong?

Upvotes: 1

Views: 1664

Answers (1)

glenn sayers
glenn sayers

Reputation: 2414

Try implementing (if it isn't already) one of the UIWebView delegate methods. The WebView may not be fully initialised by the end of the didFinishLaunchingWithOptions method.

In the .m file for your viewcontroller, add:

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

EDIT: the webViewDidFinishLoad delegate method may actually work better for this.

Upvotes: 3

Related Questions