Brendon
Brendon

Reputation: 41

How to listen to in objective c UIWebView when the javascript function is triggered

How do I listen in Objective C to listen whether the javascript method is invoked?

E.g.in javascript:

<script>
function someJsFunction(){}
</script>

How do I implement a listener in objective c using UIWebView to listen to js function being invoke.

How do I used below components? UIWebView shouldStartLoadWithRequest

How do I get the inputbox value in UIWebView?

Upvotes: 2

Views: 1629

Answers (1)

Sarju
Sarju

Reputation: 183

If you want to print console messages in js through objective c then you can use below code.

//fetch JSContext
//webView is object of UIWebView , in which your js files are already injected
JSContext *context =  [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//evaluate script on context object
[context evaluateScript:@"var console = {};"]; // make console an empty object
// when ever you use "console.log('')" in your JS it will call below block
context[@"console"][@"log"] = ^(NSString *message)
{
    NSLog(@"Console msg from js:%@", message);
};

To execute js function from objective c use below code.

NSString *evalScript = [NSString stringWithFormat:@"someJSFun(%@)",param];
[context evaluateScript:evalScript];

Now if you want to call objective c function from your JS , you can use block like below.

//Suppose you want to call "someObjCFun(param)" from your js then 
context[@"someObjCFun"]= ^(JSValue *message)
{
    //TODO
    //This block will be executed when you will call 'someObjCFun(param)' from your js
};

So if you want your textbox value in objective c , just use block like above and pass textbox value as parameter.

P.S. Your JS should be injected in UIWebView.

Upvotes: 3

Related Questions