将objective-c对象传递给javaScript函数

时间:2017-03-30 02:37:35

标签: ios objective-c

将自定义的Objective-C对象传递给JSContext,因此我们可以在js中调用object的方法,但我想将它传递给javaScript函数,然后在这个函数中我可以调用该对象的方法

function myJs(para){
    para.myMethod();
    //this para is an customed objective-c object which had implemented JSExport protocol
}
// call that js function
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"myJs(%@)", para]];

然而它不起作用,有没有办法实现它?

1 个答案:

答案 0 :(得分:0)

没有选项可以直接从javascript调用Objective-C方法,但您可以通过从javascript调用URL并使用webView:shouldStart​Load​With​Request:​navigation​Type:​委托方法捕获它来实现此目的。

只需从javascript进行网址重定向并在委托中捕获它,请检查以下代码

  // This function is called on all location change :
  - (BOOL)webView:(UIWebView *)webView2 
          shouldStartLoadWithRequest:(NSURLRequest *)request 
          navigationType:(UIWebViewNavigationType)navigationType {

    // Intercept custom location change, URL begins with "js-call:"
    if ([[[request URL] absoluteString] hasPrefix:@"js-call:"]) {

      // Extract the selector name from the URL
      NSArray *components = [requestString componentsSeparatedByString:@":"];
      NSString *function = [components objectAtIndex:1];

      // Call the given selector
      [self performSelector:NSSelectorFromString(functionName)];

      // Cancel the location change
      return NO;
    }

    // Accept this location change
    return YES;

  }

这是有助于实现这一目标的优秀tutorial