24

I am new programmer to objective C. I added some html file to Objective C. In this html file contains simple javascript function. I need to call that Function through thw objective C code. I tried lot of time by using google. But I could not find real way to do it. Bellow Contains html File :

<!DOCTYPE html>
<html>
    <head>
        <script>
            function myFunction()
            {
                alert("Hello World!");
            }
            </script>
    </head>

    <body>
        <button onclick="myFunction()">Try it</button>
    </body>
</html>

I called this function like this : Is it correct or wrong ?? If it wrong, how to do this. Please help.

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()"];
5
  • 1
    Does the alert show or not? Commented Jan 15, 2013 at 9:08
  • When I click button, its showing. But I want to call that function programmatically. Commented Jan 15, 2013 at 9:12
  • What are you trying to achieve? Is your application HTML5 type? Why not using native UIKit? Commented Jan 15, 2013 at 9:12
  • try [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"]; first, make sure it's not the problem of myFunction() Commented Jan 15, 2013 at 9:17
  • My purpose is to pass parameters to html(javascript) through objective c. I want to show html page like a report. So I want to call javascript function with parameters.So I tried simple code like this. Im not used native UIKit. @pbibergal Thanks Commented Jan 15, 2013 at 9:19

6 Answers 6

33
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:

Sign up to request clarification or add additional context in comments.

6 Comments

Really thank for your answer. It is 100% working. Thank again.
The answer is very much right. I am giving extra functionality to that Thank you!!
Please let us know how to do with iOS 8 wkwebview?
@moonlight I'm trying to make this code work, just to add some feature in my ios app (and I'm used to android) but path is nil (of course i change "first" to the name of my file : homePage) do you know why is that? and if i want to use this code in ApplicationDelegate, should I change webView to self.viewController.webView?
Can we execute a jsContext on a URL without having webView open?
|
12
<!DOCTYPE html>
<html>
<head>

    <script type="text/javascript" charset="utf-8" src="your.js"></script>
    <script type="text/javascript" charset="utf-8" src="andYourJsfileName.js"></script>

    <script>
        function myFunction('yourParameter') 
        {
            // do your javascript operation

            //alert("my Hello World!");
            return value;
        }

    </script>
</head>

<body>
    <!--button onclick="myFunction()">Try it</button-->
</body>

Add a html file to project folder. Add your javascript file also to project folder.

After adding the html file and this native code to your viewController.m

-(void)loadMyWebView {
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 100, 200)];
    NSString *path;
    NSBundle *thisBundle = [NSBundle mainBundle];
    path = [thisBundle pathForResource:@"first" ofType:@"html"];
    NSURL *instructionsURL = [NSURL fileURLWithPath:path];

    NSString* htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    webView.delegate=self;

    [webView loadHTMLString:htmlString baseURL:instructionsURL];
    // [self.view addSubview:webView];  (if you want to access the javascript function and don't want to add webview, you can skip that also.)
}


- (void)webViewDidFinishLoad:(UIWebView*)theWebView {
    NSString* returnValue =[theWebView stringByEvaluatingJavaScriptFromString:@"myFunction('pass your parameter')"];
    NSLog(@"returnValue = %@ ",returnValue);
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{

    NSLog(@" didFailLoadWithError");
}

Call this in your didLoad method [self loadMyWebView];

Here you can add any javascript file to the project and include it to the html file. You can call javascript function inside the tag. (exactly as you used to call js functions. )

You can pass any parameter to javascript function and return anything to objective function.

Remember ::: After adding all js file don't forget to add them to Copy Bundle Resources

To avoid warning ::: remove them from Compile Sources

1 Comment

calling ObjectiveC from Javascript :: blog.techno-barje.fr/post/2010/10/06/…
9

One can use JavaScriptCore framework to run JavaScript code from Objective-C.

#import <JavaScriptCore/JavaScriptCore.h>

...

JSContext *context = [[JSContext alloc] init];
[context evaluateScript: @"function greet(name){ return 'Hello, ' + name; }"];
JSValue *function = context[@"greet"];
JSValue* result = [function callWithArguments:@[@"World"]];
[result toString]; // -> Hello, World

Here is a demo:

https://github.com/evgenyneu/ios-javascriptcore-demo

2 Comments

@Evengii As mentioned in bignerdranch.com/blog/javascriptcore-example , could this lead us to rejection of our app from Apple.
@ViruMax - Your Big Nerd Ranch link is broken. I found a copy of the blog entry on the Wayback Machine: web.archive.org/web/20170611231808/https://www.bignerdranch.com/…
2

FileName.js :

function greet() {
    hello(“This is Javascript function!”);
}

Copy this file into Bundle resources.

Now #import <JavaScriptCore/JavaScriptCore.h> in header file

 @property (nonatomic,strong) JSContext *context; // Declare this in header file

       // This code block goes into main file
        NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"js"];
        NSString *scriptString = [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:nil];

        self.context = [[JSContext alloc] init];
        [self.context evaluateScript:scriptString];

        self.context[@"hello"] = ^(NSString text) {
            NSLog(@"JS : %@",text);
        }

        JSValue *function = self.context[@"greet"];
        [function callWithArguments:@[]];

This code block worked for me. It displays "This is Javascript function!" in console. Hope this works!

Comments

1

Try this:

NSString *jsCallBack = [NSString stringWithFormat:@"setPhoto('%@')",profileImgPath];

[webView stringByEvaluatingJavaScriptFromString:jsCallBack];

Comments

0

demo.js file:

function say(data) {
  return data;
}

ViewController.m

- (NSString *)invokeJS {

    NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"js"];
    NSLog(@"path: %@", scriptPath);
    NSString *script = [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:nil];
    
    self.context = [[JSContext alloc] init];
    [self.context evaluateScript:script];
    
    JSValue *function = self.context[@"say"];//invoke function name
    JSValue *data = [function callWithArguments:@[@"Hello World"]];//invoke function argument
 
    NSString *result = [data toString];//the result: Hello World

    return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.