How to Call JavaScript Function in Objective C

How to call JavaScript Function in objective C

NSString *path;
NSBundle *thisBundle = [NSBundle mainBundle];
path = [thisBundle pathForResource:@"first" ofType:@"html"];
NSURL *instructionsURL = [NSURL fileURLWithPath:path];
[webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];

NSString * jsCallBack = [NSString stringWithFormat:@"myFunction()"];
[webView stringByEvaluatingJavaScriptFromString:jsCallBack];

[webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];

If all this code called from single place, than it won't work, because page load is asynchronous and page with JavaScript code is not ready at that moment.
Try to call this methods [webView stringByEvaluatingJavaScriptFromString:@"myFunction()"]; in UIWebViewDelegate callback method –webViewDidFinishLoad:

How to call javascript code from Objective - C code?

You can load your js using

[_webView loadHTMLString:@"<script src=\"your.js\"></script>" baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];

and then in webViewDidFinishLoad you can call function and pass parameters as follows

NSString *javascriptString = [NSString stringWithFormat:@"yourFunction('%@','%@')",firstVar,secondVar];
[_webView stringByEvaluatingJavaScriptFromString:javascriptString];

Hope it Helps :)

Call Javascript function with parameters from iOS ObjC

You need to build a string containing the passed argument and use that as parameter for evaluateJavascript.
Like this:

-(void) callJavascriptFunc: (NSString*)val{
NSString* script = [NSString stringWithFormat:@"exampleFuncName('%@', '\(someConstant)')", val];
[self.webview evaluateJavascript:script completionHandler: nil];
}

Depending on where the value of the parameter comes from, however, you should make sure that no code injection is possible!

how to call a javascript function from my custom CDVPlugin class (Objective C Language)

I found the answer if we want to call any javascript method call it with evalJs which is declared in CDVCommandDelegateClass and can write the name of the function as string with semicolon

In Cordova :
we can use evaluateJavaScript method like this

[self.commandDelegate evalJs:@"callCustomMethodJs();"];



Related Topics



Leave a reply



Submit