What is JSBridge

It is mainly to provide JavaScript with the interface to call Native functions, so that the front-end part of mixed development can conveniently use Native functions, which is a bridge between Native and non-native. Its core is to build a two-way communication channel between Native and non-native messages. Usage:

H5 directly calls the H5 receiving method on this object through the Native methodCopy the code
Native calls Native H5 H5 binds the JSBridge to the window and Native directly calls the Native receiving method of this objectCopy the code

Two, JSBridge use

  1. Native follows the WKScriptMessageHandler protocol and implements its proxy methods to load and display webViews
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
Copy the code

2. Inject objects in Native’s life cycle. When the front end calls its methods, Native can capture them

-(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; / / injection [self. WebView. Configuration. UserContentController addScriptMessageHandler: self name: @ "method of defining the H5"]. } -(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; / / remove [self. WebView. Configuration. UserContentController removeScriptMessageHandlerForName: @ "method of defining the H5"]. }Copy the code

3. Finally, deal with concrete logical things in the proxy method

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { [super userContentController:userContentController didReceiveScriptMessage:message]; If ([message.name isEqualToString:@"nativeBridge"]) {NSLog(@" data passed by the front end %@: ",message.body); // Native logic}}Copy the code

3. Block URL SCHEME

The Web sends a URL Scheme request in some way (for example, iframe.src). After that, Native intercepts the request and performs related operations according to the URL SCHEME (including the parameters). • Sending the URL SCHEME using iframe.src may cause hidden problems of URL length. • Creating a request takes some time, which is longer than injecting the API to invoke the same function. Therefore: JavaScript calls Native are recommended to use the injection API

     NSString *jsStr = [NSString stringWithFormat:@"reload()"];
       [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {       
       }];
Copy the code

If there is any mistake in my understanding, please be sure to point out. Thank you very much!