Three ways of interaction between JS and native OC

Three Interactive Ways between JS and Primary OC

When you are working on a project, you should also encounter the need for communication between h5 and OC to achieve a specific effect, so I summarize the interaction between the two recently used ways:

  • By intercepting the URL in the proxy method of UIWebView
  • Implemented by JavaScript Core. Framework with OC
  • Intercepting url by ajax

    1. First, let's talk about the most common way to implement the first way (by intercepting URLs in UIWebView's proxy method). This way is to get the required URL in the webview proxy method, and then process it according to the special fields specified in the obtained url, as follows:
      -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
      {
      // The first way of interaction
      NSString *urlStr = request.URL.absoluteString;
      if ([urlStr rangeOfString:@"baidu"].location!=NSNotFound) {
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@ "first way" delegate: self cancelButton Title: nil other Button Titles:@ "confirm", nil];
      [alertView show];
      }
      return YES;
      }
    2. Then we will talk about how javascript Core. framework is implemented. First, we use JSContext to get the Javaascript execution environment of the UIWebView in UIWebView.
  _webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    _webview.backgroundColor = [UIColor lightGrayColor];
    _webview.delegate = self;
    [self.view addSubview:_webview];

    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURL *localUrl = [[NSURL alloc] initFileURLWithPath:htmlPath];
    [_webview loadRequest:[NSURLRequest requestWithURL:localUrl]];


    //The second way of interaction
    JSContext *context = [_webview  valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"button2Click22"]=^(){
            NSArray *args = [JSContext currentArguments];
            for (JSValue *jsVal in args) {
                if([[NSString stringWithFormat:@"%@",jsVal] isEqualToString:@"duijieyu"])
                {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"The second way" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Determine", nil];
                    [alertView show];
                    break;
                }
            }
            JSValue *this = [JSContext currentThis];
            NSLog(@"this: %@",this);
    };

Then in the javascript execution environment, define a corresponding js function, as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Document</title>
    <link href=" " rel="stylesheet"/>
    <script src="jquery.js" type="text/javascript"></script>
</head>
<body>
</br></br>

<a href="javascript:;" id="btn2" style="font-size: 18px" onclick="button2Click()">The second way of interaction( JavaScriptCore)</a></br>
<script type="text/javascript">

function button2Click()
{
    button2Click22("duijieyu");//Docking captured in oc
}
</script>
</body>
</html>

The corresponding details need to be changed to those specified in your own project.

  1. Then let's talk about the way to communicate with ajax. Android's pain with h5 pages through AJAX is particularly easy, but if iOS wants to interact with h5 through ajax, it can use this method. (Now I can find a way, if there is a good way, please give me advice.) First of all, this method Need to add a bridge file in the project, as an interactive bridge, and then through Ajax with the prescribed good links and fields in the bridge file corresponding to the field conversion, finally ViewController through the bridge file to obtain the corresponding information for processing, the code is as follows:
<script type="text/javascript">
$('#btn3').on('click',function(){
    $.ajax({
        type : 'get',
        url : 'http://myApp.example.org/alert?title=Test%20from%20AJAX&message=this%20is%20a%20message%20from%20an%20AJAX%20request"',
        data:'',
        dataType : 'json',
        timeout : 300,
        success:function(data) {
          $('#btn').html('Order me.');
        },
        error:function(errMsg) {
            $('#btn').html('Error');
        }
    })
})
}


#pragma mark - NativeActionDelegate
-(NSDictionary *)handleAction:(NativeAction *)action error:(NSError *__autoreleasing *)error
{
    if ([action.action isEqualToString:@"alert"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[action.params objectForKey:@"title"] message:[action.params objectForKey:@"message"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [alertView show];
        });
        return nil;
    }
    return nil;
}

Note: Don't forget to set up a proxy for bridging files.
Attached demo address:

Keywords: Javascript JQuery Android iOS

Added by andreiga on Mon, 15 Jul 2019 21:06:28 +0300