nukl
nukl

Reputation: 10521

Cocoa WebView: Cannot call Specific Javascript method using `callWebScriptMethod:`

I am loading a page into a WebView. The page has this little-test Javascript:

<script type="text/javascript">
function test(parametr)
{

  $('#testspan').html(parametr);

}

var bdu = (function(){
 return {
  secondtest: function(parametr) {

  $('#testspan').html(parametr);

  }
 }
})();
</script>

The problem is that I can't call the "secondtest" function from cocoa

this is perfectly work:

[[webview1 windowScriptObject] callWebScriptMethod:@"test" withArguments:arguments];

and this is not working:

[[webview1 windowScriptObject] callWebScriptMethod:@"bdu.secondtest" withArguments:arguments];

What would cause this problem and how do I fix it?

Thanks

Upvotes: 4

Views: 1711

Answers (3)

Olivier Bonal
Olivier Bonal

Reputation: 61

"callWebScriptMethod" is meant to call a given method on a given webscript (i.e. javascript) object. On your second line you want to call the "secondTest" method on the javascript object named "bdu". The way to do this is to:

  1. Get the bdu object from your window object:

    WebScriptObject* bdu =[[webview1 windowScriptObject] valueForKey:@"bdu"];

  2. Call the "secondTest" method on the bdu object:

    [bdu callWebScriptMethod:@"secondtest" withArguments:arguments];

Upvotes: 1

worriorbg
worriorbg

Reputation: 351

I was struggling with this for some time in Cordova MacOSX and here is the solution I found and works for me:

JavaScript:

CordovaBridgeUtil.isObject = function(obj) { return obj.constructor == Object; };

ObjectiveC:

WebScriptObject* bridgeUtil = [win evaluateWebScript:@"CordovaBridgeUtil"];
NSNumber* result = [bridgeUtil callWebScriptMethod:@"isObject" withArguments:[NSArray arrayWithObject:item]];

Upvotes: 2

Yuji
Yuji

Reputation: 34185

callWebscriptMethod:(NSString*)name withArguments:(NSArray*)args:

does not evaluate name as a Javascript expression. So it can't parse bdu.secondtest: it doesn't look up bdu first, then get the entry secondtest in it.

Instead, just use evaluateWebScript:.

Upvotes: 0

Related Questions