Pass variables from Objective-C to javascript function?

I have a simple javascript function that takes two variables. I need to pass two variables that I already have in an Objective-C (iOS) application for this javascript function. My line of code to run javascript:

[webView stringByEvaluatingJavaScriptFromString:@"onScan()"]; 

The javascript function simply applies two variables to the HTML form and submits it. Of course, I get undefined in my form since there are no variables. 8-) I could not find a lot of documentation about this, but maybe I was looking for the wrong place?

FWIW, my Objective-C variables are strings. My javascript onscan(a,b) function onscan(a,b)

UPDATE:

I managed to get this working by putting single quotes around each of the variables passed to the javascript function. Updated code:

 [webView stringByEvaluatingJavaScriptFromString:@"onScan('%@','%@')",a,b]; 
+6
source share
1 answer

stringByEvaluatingJavaScriptFromString: takes an NSString value, so all you have to do is combine the strings with stringWithFormat: and format the %@ object as shown below:

 NSString *stringOne = @"first_parameter"; NSString *stringTwo = @"second_parameter"; NSString *javascriptString = [NSString stringWithFormat:@"onScan('%@','%@')", stringOne, stringTwo]; [webView stringByEvaluatingJavaScriptFromString:javascriptString]; 

Check out the Apple documentation for NSString , this is insanely useful!

+9
source

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


All Articles