2

I am developing a web app that is being displayed in a UIWebView. The app is loaded locally, i.e, not from a web server. I am communicating from Javascript to ObjC via the shouldStartLoadWithRequest: method in the UIWebViewDelegate protocol.

The last thing I need is to be able to call Javascript functions from ObjC without any page reloads. I hope this is possible.

4 Answers 4

8

Well, you can call

-[UIWebView stringByEvaluatingJavaScriptFromString:]

whenever you like, not just in response to a delegate method.

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

1 Comment

OMG I knew this already. Ha, it's really late here and I had got myself into a panic over having to start the project all over and completely forgot. Thanks. I can go to bed and rest easy now.
4

You can call any javascript function in your webview by simply using the stringByEvaluatingJavaScriptFromString method on your webview after you've loaded the webview:

[self.myWebView stringByEvaluatingJavaScriptFromString:@"myJavaScriptFunction(123.0)"];

You don't need to reload the webview to send this message (just don't release the webview before you're done).

Comments

1

Could't you just do this by doing a "loadRequest", and passing it an NSURL with contents like like:

javascript:myFunction("MyParameter");

It should call your function, but not reload the page.

Comments

0

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

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.