iosobjective-cwkwebviewevaluatejavascript

Call Javascript function with parameters from iOS ObjC


I am trying to call Javascript function with params from iOS using 'evaluateJavascript', everything works fine but the params value is not being sent, please see the code below

-(void) callJavascriptFunc: (NSString*)val{
  //Example val is "Apple" string
  [self.webview evaluateJavascript:@"exampleFuncName(val, '\(someConstant)')" completionHandler: nil];
}

Javascript:

exampleFuncName(value1: string, value2: string){
   console.log("values == ", value1 + " , " + value2)
}

Console: ReferenceError: Can't find variable: val

I am able to call the function but am not able to pass the variable. Is there an issue with syntax while calling a function with evaluateJavascript

Note: I have checked val has a value.


Solution

  • You need to build a string containing the passed argument and use that as parameter for evaluateJavascript. Like this:

    -(void) callJavascriptFunc: (NSString*)val{
        NSString* script = [NSString stringWithFormat:@"exampleFuncName('%@', '\(someConstant)')", val];
        [self.webview evaluateJavascript:script completionHandler: nil];
    }
    

    Depending on where the value of the parameter comes from, however, you should make sure that no code injection is possible!