There’s always a reason for a skill point. Jockeyjs.js is an easy example to understand.

Article Summary:

  • 1. Basic concepts of hybrid
  • 2. Interaction between the front-end and the client
  • 3. Realize the interaction between the front-end and the client
  • 4. Front-end interaction implementation concerns
  • 5. Summary

1. Basic concepts of hybrid

1.1 What is a hybrid?

Hybrid refers to the hybrid development mode of front-end and client, and some aspects may also involve the server side. The bottom layer of Hybrid relies on the container (WebView) provided by Native, and the upper layer uses HTML&CSS &JS for business development.

1.2 What is a WebView?

A component in an app that is similar to a small browser kernel. Native provides container boxes for loading H5 pages.

The figure illustrates two ways in which h5 page resources can be utilized
① Pack static resources into the APP.
The front-end provides the code to Native, and the Native client takes the front-end static page and stores it in the APP in the form of files. In this mode, if the front-end static page needs to be updated, the client needs to download static resources from the server. That is, every time the client opens it, it needs to go online to check whether there is any update package, download the compressed package, decompress and update static resources.
Advantages: Because resources are locally accessed through the File protocol, the reading speed is very fast, and pages can be reasonably displayed in off-network mode.
  • This involves a server – side static resource pack management system.
  • At the same time, H5 resources are statically stored in Native and read in the form of file, so there is cross-domain request initiated by H5 to the remote end. Therefore, H5 requests need to be forwarded through Native for a layer of proxy.
  • The more static resources, the larger the native package (so this mode is more suitable for scenarios with stable product functions, high experience requirements and frequent iterations).
② Online URL (more H5)
Deploy resources online, and Native opens a new WebView to request online resource display (the same process as entering URL in browser to view pages)
Advantages: Loading on demand, the page used by the user will be updated, and the request can be sent without going through Native as a proxy.
  • Inevitably, it takes time to request online resources, so there will be an instant blank screen (especially in weak network mode).
  • No content is displayed in disconnected mode.
③ Two modes of resource loading
Local read: through file protocol
Read online: Load a resource through an HTTP or HTTPS request

1.3. The significance of hybrid?

Rapid iterative development of updates. (No app review is required, haha, because the operation authority of the mobile phone is not high, so no review is required?)

Hybrid development efficiency, low cost, cross-platform,ios and Android shared a set of H5 code. (ios and Android interface is the same)

From the perspective of business development, Hybrid has no version problems and can fix bugs in time (compared with APP).

2. Communication between the front-end and the client

The container box provided by Native is used to load H5 pages. Then how should H5 pages interact with Native?

The interaction between the front-end and the client is described as follows:

  • JS access the client’s ability to pass arguments and callback functions.
  • The client returns the content via a callback function.

The front-end page interacts with native through the Schema protocol. (In fact, Native can capture all requests made by the WebView. The significance of this protocol is that the APP can be opened directly in the browser.)

2.1 What is the Schema Protocol?

General description: Scheme is an in-page jump protocol. By defining its own Scheme protocol, Native intercepts this request and processes it according to requirements, so it is very convenient to jump to various pages in app.

You can perform the following operations to support custom URL schemes:

  • Define the format of the application Schema URL.
  • Register the application Schema URL scheme so that the system directs the appropriate URL to the application.
  • The application processes the received schemaURL.

Some URL Scheme

www.zhihu.com/question/19…

A snippet of code, source: github.com/tcoulter/jo…

// The main function of this code is that the front end sends messages to the client through a special protocol. The client intercepts the request and processes dispatchMessage:function(type. envelope) { // We send the message by navigating the browser to a special URL. // The iOS library will catch the navigation, prevent the UIWebView // from continuing, and use the datain the URL to execute code
    // within the iOS app.

    var src = "jockey://" + type + "/" + envelope.id + "?" + encodeURIComponent(JSON.stringify(envelope));
    var iframe = document.createElement("iframe");
    iframe.setAttribute("src", src);
    document.documentElement.appendChild(iframe);
    iframe.parentNode.removeChild(iframe);
    iframe = null;
}Copy the code

2.2. Specific H5 communicates with Native, JS to Native?

The communication between JS and Native is generally to create such urls which are captured and processed by Native.

2.3. Native to H5 page, Native to JS?

So can Native call the method on the Window object in the WebView that it provides?

Native can call methods that are mounted on the Window object as previously agreed upon by the front end. (Did it happen?)

(Photo source click)

/ Send an event to JavaScript, passing a payload.
// payload can be an NSDictionary or NSArray, or anything that is serializable to JSON.
// It can be nil.
[Jockey send:@"event-name" withPayload:payload toWebView:webView];

// If you want to send an event and also execute code within the iOS app when all
// JavaScript listeners have finished processing.
[Jockey send:@"event-name" withPayload:payload toWebView:webView perform:^{
  // Respond to callback.
}];Copy the code

3. Realize the interaction between the front-end and the client

There are two forms of interaction between front-end and Native:

① URL Schema (front-end defines objects first, and interactive methods)

(2) The client defines the object and injects global variables.

JavaScriptCore is an open source project implemented by C++. Using the JavaScriptCore framework provided by Apple, you can execute Javascript code in Objective-C or C-based programs and insert custom objects into the Javascript environment. Can be used directly after JavaScriptCore from iOS 7.0, data: https://developer.apple.com/documentation/javascriptcore.

3.1URL Schema (Front-end defines objects and interaction methods)

<! DOCTYPE html> <html> <head> <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1">
    <title>Document</title>
</head>
<body>
    <button id="btn1"</button> <scripttype="text/javascript">
        function send(type, payload,callback) {
            var envelope = {
                id: id,
                type: type,
                host: host,
                payload: payload
            };
            window.myapp.[envelop.id] = callback;
            var src = "myapp://"+envelope.id + "?"+ encodeURIComponent(JSON.stringify(envelop)); // Tells the client the function to call. After the function is executed, tells H5 to run window.myApp.[envelop.id]. Var iframe = document.createElement() var iframe = document.createElement()"iframe");
            iframe.setAttribute("src", src);
            document.documentElement.appendChild(iframe);
            iframe.parentNode.removeChild(iframe);
            iframe = null;
        }

        document.getElementById('btn1').addEventListener('click'.function () {
            send("scan", {}, (payload) => {
                console.log("hi")
            })
        })
    </script>
</body>
</html>Copy the code

Usually, the code implementation will encapsulate the send function, and the front-end only needs to implement the function agreed with native.

getPort: function() {
    window.send("getPort", {}, (payload) => {

    });
},
login: function(args = {}) {
    window.send("login", args, (payload) => {

    });
},Copy the code

3.2. Client defines objects and injects global variables (client injects global variables for H5 use)

// The page calls an undeclared method that Native actually injected into the window object. Myapp. GetPort (data, (payload) => {}); myapp.login(data, (payload) => { });Copy the code

The differences between the two methods are the client or h5 predefined objects, and the interaction methods.

4. Front-end interaction implementation concerns

Source: github.com/tcoulter/jo… (The following code example is based on URL Schema)

4.1. Navigation bar Settings

The navigation bar is usually a native implementation, and has a back button to prevent the page from feign death, that is, the page can be frozen back.

Meanwhile, Native needs to provide APIS for simple customization of H5 (such as close button, share button, favorites button, etc.).

setBarBack() {
    Jockey.send("setBarBack", {
        "bar": {
            "position": "left"."cliekEvent": "onBack",}}); Jockey. Off (Jockey.'onBack'); Jockey. On (Jockey.'onBack', () => {
        history.back()
    });
},Copy the code

4.2. Jump is one of the required APIS of Hybrid. For the front-end, there are the following jumps:

① H5 jumps to Native interface

② H5 opens a Webview to jump to the H5 page.

Jump with native method, generally is to do the page animation switch.

As shown in the figure, we usually only use the lower part of the navigation bar, but we pay attention to the navigation bar of the page. H5 terminal can register events and listen to the events of native navigation bar (not necessary).

4.3 Obtaining Basic Information

In the mode with user system, H5 page can get basic login information from Native. Native itself saves user information and provides interface for H5 to use.

function getInfo() {
    return new Promise((resolve, reject) => {
        Jockey.send("getInfo", {}, (payload) => {
        
        });
    });
},Copy the code

4.4 Invoking Native Functions

Camera, mobile phone page landscape display or portrait display, etc.

4.5 About Debugging

Android: Enter Chrome ://inspect/#devices (native open debug mode), of course, Android can also use the emulator, but the performance of the real machine is too different from Android, or recommend to use the real machine test.

IOS: Need a Mac, then open Safari, open development mode in preferences, then click open Safari browser, view the menu bar development menu (native has debug mode enabled)…

5. Summary

This article is just a simple understanding of hybrid. The examples in this article are rough and inaccurate, so I would like to ask you to correct them. For those interested in learning more about the design and implementation of the front-end of Hybrid technology, see Resources

References:

www.cnblogs.com/yexiaochai/…

www.cnblogs.com/yexiaochai/…

www.cnblogs.com/yexiaochai/…