3

i am working with java script in objective - C.

Following is my code :

NSString *javascript = @"testfunction = function(){ jQuery.getScript(\"https://www.myserver.com/myscript.js\").done(function(script,textStatus){$testvalue = 10; return $testvalue; }).fail(function(jqXHR,settings,exception){\n alert(exception);});}";

[webview stringByEvaluatingJavaScriptFromString:javascript];

NSString *value = [webview stringByEvaluatingJavaScriptFromString:@"testfunction();"];
NSLog(@"Value of Value : %@",value);

now The Problem is:

i want value in my value variable how can i get it?

3 Answers 3

1

add delegate to your webview

_webView.delegate =self;

use this code

NSString *fName = [[NSString alloc] initWithFormat: @"demo()"];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:fName];
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for reply. but it's basic think what i am doing but still i am not getting value of that variable into my objective c code
1

download code example

follow these step:

create JS file demo.js and add code

var hello = function(str){
   return str;
};

add UIWebView => To embed JavaScript in a dummy html file and load that into the UIWebView

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

Here is the code to make JS call

NString *str=@"hi JavaScript";
NSString *function = [[NSString alloc] initWithFormat: @"hello(%@)", str];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:function];

Now, there is one important safety tip to make this actually work: The UIWebView must actually be loaded a view. It doesn’t have to be visible, but in order for the WebKit engine to execute the JS, it must be on a view.

This might helps you :)

1 Comment

thanks for quick reply i already did it. but i want the value into my objective c variable from javascript how can i ?
0

You can use UIWebView's delegate method webView:shouldStartLoadWithRequest:navigationType: to intercept URL requests. Make a fake request when you need to return some data from JS function, intercept it, handle, and return NO.

Read here for details.

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.