Cocoa WebView: Cannot invoke custom Javascript method with `callWebScriptMethod:`

I am loading a page in a webview. There is this little test Javascript on the page:

<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 cannot name the function "secondtest" from cocoa

this works fine:

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

and this does not work:

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

What can cause this problem and how to fix it?

thanks

+4
source share
3 answers

I struggled with this for a while in Cordoba 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]]; 
+2
source

"callWebScriptMethod" is intended to call this method on a given webscript object (ie javascript). On the second line, you want to call the "secondTest" method in a javascript object named "bdu". The way to do this is:

  • Get the bdu object from your window object:

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

  • Call the second test method for the bdu object:

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

+1
source

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

does not evaluate name as a Javascript expression. Therefore, it cannot parse bdu.secondtest : at first it does not look up bdu , and then gets the secondtest entry in it.

Instead, just use evaluateWebScript:

0
source

Source: https://habr.com/ru/post/1302361/


All Articles