This is the first day of my participation in the August Text Challenge.More challenges in August

Simple to understand

In the previous H5 project, Jsbridge was used to interact with Native, such as evoking the sharing function of Native. Jsbridge is literally the bridge between Native and H5 pages. In fact, it is a library for the encapsulation of native and H5 interaction methods, mainly including the processing of the interaction compatibility of each version, as well as the encapsulation of the implementation differences between ios and Android.

The principle of

Call native js

The native way to call JS is relatively simple. WebView provides an API to execute JS code.

webView.evaluateJavascript()
Copy the code

Js call native

While JS calls native, there is no direct API to call. So the need for lovely program ape thought of the curve to save the country, to achieve JS call native. There are two mainstream schemes:

1. Native directly injects its API into the window object of the H5 page.

Android Android 4.2: Use addJavascriptInterface. Android 4.2 and later: use @javascriptInterface. IOS UIWebView uses postBridgeMessage and WKWebView uses addScriptMessageHandler

2. Both sides define an agreement, then in some convenient protocol information (you need to call the method name and parameters, the callback, etc.) of the event is triggered when the event to intercept, so as to get to the need to call native method name, the required parameters, and after the callback method, etc., finally complete a native method calls.

Android two ways:

1. Use shoudOverrideUrlLoading to intercept the URL, parsing;
2. Intercept data parameters carried by overriding any of the prompt,alert, or confirm methods. Prompt is usually used, as it is rarely used in JS.

IOS can initiate this request in two ways:

1. location.href;
2. The iframe SRC.

Generally, iframe is used. Because of the location. If the href is called several times in a row, native will only get the last value and the previous request will be ignored. The specific implementation is as follows: in H5 on the page, create a hidden IFrame, SRC starts with Jsbridge protocol, and use the method name and parameter key-value pair of the invoked Native as the PARAMETER URL. After intercepting the URL, Native will parse the URL and then execute the corresponding Native method.

conclusion

Above is my understanding of Jsbridge mainly through some articles. The understanding is relatively simple, especially the implementation details, there are inaccuracies, welcome to correct.