Hybrid App implementation principle

Currently, the apps on the market have frequent iteration changes. In order to meet business needs, they basically use Hybrid to achieve fast online and offline business. The characteristics of H5's flexible development and online hot update mechanism are very suitable for frequent business iterations. We need a complete Hybrid technology architecture solution to make full use of H5's powerful development and iteration capabilities, and to give H5 powerful underlying capabilities and User experience, while being able to reuse existing mature Native components.

Hybrid technology principle

The core point of Hybrid is how to deal with the two-way communication layer between Native and H5. In fact, it can also be understood that we need a set of cross-language communication solutions to complete Native (Java/Objective-c/…) and JavaScript. communication. This is what we call JSBridge. The key to Hybrid App implementation is to use WebView as a container to directly host Web pages.

The web container is the link between Native and H5, which is divided into JavaScript notification to Native and Native notification JavaScript.

JavaScript notification Native

  • The principle of API injection is actually that Native gets the JavaScript environment context and directly mounts objects or methods on it, so that js can be called directly. Android and IOS have corresponding mounting methods respectively.
  • For prompt/console/alert interception in WebView, prompt is usually used, because this method is used less frequently in the front-end, and there is less conflict;
  • WebView URL Scheme jump interception

The principles of the second and third mechanisms are similar. They are all through the interception of WebView information transmission, so as to achieve communication. Next, we will mainly elaborate from the five aspects of principle-custom protocol-interception protocol-parameter transfer-callback mechanism. The third scheme-URL blocking scheme.

Implementation principle

Clients can monitor and capture network requests sent in WebView

Agreement customization

We need to formulate a set of URL Scheme rules. Usually our request will start with the corresponding protocol, such as the common https://xxx.com or file://1.jpg, which represents different meanings. We can customize the protocol type request as:

xxcommand://xxxx?param1=1¶m2=2
Here are a few points to note:

(1) xxcommand:// is just a rule, which can be formulated according to the business to make it meaningful. For example, we define xxcommand:// to be common to all apps of the company, and it is a common tool agreement:

xxcommand://getProxy?h=1
and define xxapp:// as a separate service agreement for each App.

xxapp://openCamera?h=2
Different protocol headers represent different meanings, so that you can clearly know the applicable scope of each protocol.

(2) Do not use location.href to send here, because there is a problem with its own mechanism that multiple concurrent requests at the same time will be merged into one, causing the protocol to be ignored, and the concurrent protocol is actually a very common function. We will use the method of creating an iframe to send the request.

(3) Generally considering security, it is necessary to set up a domain name whitelist or restriction in the client to prevent the company's internal business agreement from being directly invoked by a third party.

Protocol interception

The client can intercept the request sent by WebView through API:

On IOS: shouldStartLoadWithRequest
Android: shouldOverrideUrlLoading
When it is resolved that the request URL header is the specified protocol, the corresponding resource request is not initiated, but the parameters are parsed, and related functions or methods are called to complete the mapping of protocol functions.

Protocol callback

Since the essence of the protocol is actually to send a request, this is an asynchronous process, so we need to deal with the corresponding callback mechanism. Here we use the JS event system, here we will use the two basic APIs window.addEventListener and window.dispatchEvent;

When sending an agreement, register a custom event with the unique identifier of the agreement, and bind the callback to the corresponding event.
After the client completes the corresponding function, it calls Bridge's dispatch API and directly carries data to trigger the custom event of the protocol.
Through the event mechanism, development will be more in line with our front-end habits. For example, when you need to listen to the client's notifications, you only need to listen through addEventListener.

Tips: One thing to note here is that multiple repeated binding of events should be avoided. Therefore, when the unique identifier is reset, the event corresponding to the removeEventListener needs to be removed.

Parameter passing method

Since WebView has a limitation on the length of the URL, the conventional way of passing the search parameter has a problem. When the parameter to be passed is too long, it may be truncated, such as when base64 is passed or a large amount of data is passed.

Therefore, we need to formulate new parameter passing rules, we use the function call method. The principle here is mainly based on:

Native can directly call the JS method and directly obtain the return value of the function.
We only need to mark a unique identifier for each protocol, and store the parameters in the parameter pool, and then the client can obtain the corresponding parameters from the parameter pool through the unique identifier.

Native notifies Javascript
because Native can be counted as the host of H5, so it has greater authority. It is also mentioned that Native can directly execute Js code through WebView API. Such authority also makes communication in this direction very convenient.

IOS: stringByEvaluatingJavaScriptFromString

// Swift
webview.stringByEvaluatingJavaScriptFromString("alert('NativeCall')")

Android: loadUrl (4.4-)
// Call the JSBridge.trigger method in js
// The drawback of this method is that the function return value cannot be obtained;

webView.loadUrl("javascript:JSBridge.trigger('NativeCall')")

Tips: When the system is lower than 4.4, evaluateJavascript cannot be used, so the JS return value cannot be obtained by simply using loadUrl. At this time, we need to use the prompt method mentioned earlier for compatibility, and let the H5 end send data through prompt , The client intercepts and obtains data.

Android: evaluateJavascript (4.4+)
// After 4.4+, use this method to call and get the function return value;

mWebView.evaluateJavascript("javascript:JSBridge.trigger('NativeCall')",      new ValueCallback<String>() {
    
    
    @Override
    public void onReceiveValue(String value) {
    
    
        //此处为 js 返回的结果
    }
});

Based on the above principle, we have understood the most basic principle of JSBridge, and can realize the two-way communication mechanism of Native <=> H5.

Insert picture description here

JSBridge access

Next, let's sort out the resources needed on the code. The realization of this scheme, as can be seen from the above figure, can actually be divided into two parts:

JS part (bridge): Inject the implementation code of bridge into the JS environment, including some basic functions such as protocol assembly/sending/parameter pool/callback pool.
Native part (SDK): the function mapping code of bridge in the client, which realizes URL interception and analysis/environmental information injection/general function mapping and other functions.
Our approach here is to encapsulate the two parts together into a Native SDK, which is introduced by the client. When the client initializes a WebView to open the page, if the page address is in the whitelist, it will directly inject the corresponding bridge.js into the head of the HTML. This approach has the following advantages:

The codes of both parties are maintained uniformly to avoid version splitting. When there is an update, as long as the SDK is updated by the client, there will be no version compatibility issues;
the access of the App is very convenient. You only need to access the latest version of the SDK according to the document, and you can directly run the entire Hybrid solution, which is convenient for multiple applications. Fast landing in an App;
no need to pay attention to the H5 end, which is conducive to opening the bridge to third-party pages.
One thing to note here is that the call of the protocol must be executed after bridge.js is successfully injected. Since the injection behavior of the client is an additional asynchronous behavior, it is difficult to capture the exact timing of completion from the H5 side. Therefore, it is necessary to monitor the page through the client to notify the H5 side based on the above callback mechanism, and the page can be passed through the window .addEventListener('bridgeReady', e => {}) to initialize.

H5 access method in App

There are usually two ways to connect H5 to App:

(1) Online H5 , this is the most common way. We only need to deploy the H5 code to the server, as long as the corresponding URL address is given to the client, and the URL is opened with WebView to embed it. The advantages of this method are:

Strong independence, with very independent development/debugging/update/online capabilities; resources are placed on the server, which will not affect the client's package size at all; access costs are very low, and a complete hot update mechanism.

But relatively, this method also has corresponding shortcomings: it is
completely network dependent, and the page cannot be opened when offline;
the loading speed of the first screen depends on the network, and when the network is slow, the loading of the first screen is also slow;
usually, this The method is more suitable for some relatively lightweight pages, such as some help pages, tips pages, and usage guides. The features of these pages are that they are not very functional, do not require complex functional protocols, and do not need to be used offline. In some third-party page access, this method is also used, for example, our page calls WeChat JS-SDK.

(2) Built-in package H5 , which is a localized embedding method. We need to package the code and send it to the client, and the client directly decompresses it to local storage. Usually we use it on some relatively large and important modules.

Its advantages are:
due to its localization, the first screen loading speed is fast, and the user experience is closer to the original; it can run offline without relying on the network;
but at the same time, its disadvantages are also very obvious: the
development process/update mechanism is complicated and the customer is required Collaboration between the client and even the server; will increase the size of the App package accordingly;
these two access methods have their own advantages and disadvantages, and should be selected according to different scenarios.

Reference from: https://segmentfault.com/a/1190000015678155
Android: WebView and Javascript interaction (mutually calling parameters, passing values)

If you are also keen on technology, welcome to join the group and make progress together: 230274309. Share together, make progress together! Strike less and dry more! ! welcome everybody! ! ! (Don't join group of divers)

Click the link to join the group chat [The Beauty of Programming]: https://jq.qq.com/?_wv=1027&k=h75BfFCg

Or scan the code
Insert picture description here

Guess you like

Origin blog.csdn.net/u011733020/article/details/113100427