Get values from uiwebview webpage using javascript
I am working with java script in object - C.
Below 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:
I need a value in my value variable, how can I get it?
download sample code
follow these steps:
create JS file demo.js and add code
var hello = function(str){
return str;
};
add UIWebView => Insert JavaScript in dummy html file and load it in UIWebView
[self.webView loadHTMLString:@"<script src=\"demo.js\"></script>"
baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];
Here is the code to make the JS call
NString *str=@"hi JavaScript";
NSString *function = [[NSString alloc] initWithFormat: @"hello(%@)", str];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:function];
You now have one important safety tip for this to actually work: the UIWebView should actually load the view. It doesn't have to be visible, but for the WebKit engine to execute JS, it must be in the view.
This might help you :)
add delegate to your webview
_webView.delegate =self;
use this code
NSString *fName = [[NSString alloc] initWithFormat: @"demo()"];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:fName];
You can use the UIWebView
delegate method webView:shouldStartLoadWithRequest:navigationType:
to intercept URL requests. Make a fake request when you need to return some data from a JS function, intercept it, process it and return it NO
.
Read more here .