Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the Communication problem and realize the Cross-platform Development of Mobile end by JSBridge Framework

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, Xiaobian will bring you about how the JSBridge framework solves communication problems and realizes mobile cross-platform development. The article is rich in content and analyzes and narrates from a professional perspective. After reading this article, I hope you can gain something.

Cross-platform development is a trend

At present, the mainstream mobile platforms are mainly Android and iOS. In order to reuse code and save development costs as much as possible, major giants have developed their own cross-platform frameworks, such as Facebook's React-Native, Ali's Weex, Cordova, and Flutter framework introduced at this year's Google Developer Conference. Each of these frameworks has its pros and cons, but none of them have been widely adopted so far for several reasons, in my opinion:

1. The developer ecosystem is not mature enough

RN is the most concerned and ecologically active of the three cross-platform frameworks, but so far it has not reached version 1.0 (the latest release is 0.57.8), let alone Weex and Flutter as latecomers. Immature ecology means that there are few development documents and few open source controls that can be used. For example, it is difficult to do the most basic pull-down refresh and pull-up load more listviews on RN. Weex has contributed to Apache and hasn't updated release in a long time. Flutter is still in beta, and its development remains to be seen.

2. Performance issues

Although these frameworks have optimized rendering performance, they are still a little worse than native ones. RN and weex both implement a browser kernel (JSCore) by themselves, so there is an extra layer of js parsing, rendering is slower. For example, RN listview, if the amount of data is too large, it will appear stuck. Although Flutter comes with its own rendering engine, it still has some distance compared to native.

3. Compatibility issues

Although the original intention of these three platforms is to cross-platform (Write/Learn once, run everywhere), but in the actual application still need to spend a lot of energy to compatibility and adaptation, such as RN on Android low-end machine performance is not satisfactory, even once RN solid advocate Airbnb announced to give up the use of RN.

4. Development integration cost

All three frameworks need to learn the new language React/vue/dart. The biggest advantage of weex is that it is easy to get started, but the version iteration is slow, RN has a high threshold, and it is difficult to develop and debug. Integrating RN and weex frameworks will also add a lot of so files, increasing the size of the installation package (at least 10M), which does not include third-party libraries. Flutter has just come out, and not many people have applied it, and its effect remains to be seen.

Summary: Although the above self-developed cross-platform frameworks have more or less problems, cross-platform mobile development is the trend, which can save development costs, improve development efficiency, and quickly respond to business changes. The mainstream applications still use H5 and native communication to achieve cross-platform development. Both Android and iOS platforms have their own built-in browser kernel webkit framework. The essence of cross-platform is that code written in H5/JS can run in Android and IOS WebView respectively, so as to achieve the purpose that a set of code can run on both platforms.

Second, Android cross-platform development practice

The communication between Native and JS on Android platform is mainly realized by WebViewClient and WebChromeClient.

WebViewClient is used to help WebView process notifications and event requests. Its main methods are onLoadResource, onPageStart, onPageFinished, onReceiveError, shouldOverrideUrlLoading, etc.

WebChromeClient handles the event response of JS page, such as dialog box, webpage icon, website title, webpage loading progress and other events in webpage. The corresponding response methods include onJsAlert, onJsConfirm, onJsConsole, onProgressChanged, onReceiveIcon, onReceiveTitle and so on.

To implement Java and JS communication:

Solve Java debugging JS;

JS is Java.

Java calls JS via loadUrl and evaluateJavaScript.

Through webview.loadUrl("_javascript:alert ('hello world')"), you can inject js code into html pages on android platform. The loadUrl method can directly call functions defined in js, or inject js files under android's local assets directory into html pages in the form of strings, but this injection timing must wait until html pages are loaded, that is, it is called in WebViewClient.onPageFinished callback function, which is equivalent to directly referencing js resource files in html pages. For the client, java calls js is essentially a concatenation of js string process, but call loadUrl can not directly get the return value of js function, but to implement Java calls js function.

The return value of the js function can be obtained using the webview.evaluateJavaScript method, but this method is only available on android 4.4 and above. Other uses are consistent with loadUrl.

JS calls Java can be divided into three types: object mapping, URL interception, JS method interception.

Object mapping is through webview.addJavascriptInterface(new JSObject(), "javaObject"), so that js code can directly call javaObject object, thus realizing JS call Java function, but this method in android4.2 below will have security vulnerabilities, using reflection mechanism to call Android API getRuntime execution shell command to attack, such as traversing sdcard, sending SMS, installing Trojan APK, etc.

URL interception means opening a link in an html page via iframe.src, window.open, documentation.location, or href, which triggers the WebViewClient.shouldOverrideUrlLoading method in Java. Executed in JS, for example

In shouldOverrideUrlLoading, you can obtain the data transferred from JS according to the agreed protocol format (Scheme) and protocol name (Authority).

Calling alert, console, prompt, confirm and other methods in JS will trigger callbacks of WebChromeClient's onJsAlert, onConsoleMessage, onJsPrompt, onJsConfirm methods. For example, you can call in JS.

The contents of the prompt can be obtained in the message of onJsPrompt, and then the data can be obtained according to the agreed protocol format.

III. JSBridge Framework

To solve the communication problem between JS and Native, you need to use a JSBridge framework (https://github.com/lzyzsd/JsBridge) to be responsible for the communication between H5 and Java. At this time, you need to solve the following two problems:

1) How to call back after JS calls each other Java and pass responseData back;

2) JS calls Java has three methods, if you choose which method is more appropriate.

For question 1, you can define a data structure on java and js: Message={callbackId:xxx, handleName:xxx,responseData:xxx,responseId:xxx}. Save the callback function in callbackId. When JS or Java finishes processing the data callback, store the callback function saved in callbackId in responseId, and store the corresponding callback data in responseData. In this way, you can respond to the callback message after JS or Java call.

Js calls Java although there are three methods, but addJavaScriptInterface security problems generally do not recommend the use of alert, console methods in JS will be more commonly used in Html pages, confirm and prompt although not commonly used but some mobile phone system versions will have a dialog box pop-up, not common, so the better choice is url interception, you can trigger shouldOverrideUrlLoading through iframe.src.

The JsBridge framework is mainly divided into:

inject a local js file after loading the H5 page;

Register BridgeHandler in Java code to process messages sent by JS;

Define_handleMessageFromNative in the js file injected locally, which is used to receive messages passed by java;

Because client injection js is asynchronous, you need to register the Event listener in the js file and notify H5 after success.

Native calls JS, e.g. via

webview.loadUrl("_javascript:WebViewJavascriptBridge._ handleMessageFromNative('{\"callbackId\":\"JAVA_CB_2_559\",\"data\":\"just data from java\"}')");

In this way, you can call JS's handleMessageFromNative method. The data format passed is Message. CallBackId responds to js callback, which will be stored in HashMap before sending. When js callback, find the corresponding callback function according to JAVA_CB_2_559 to process js response data. The specific process is as follows:

Js calls Java and converts the passed information into a sendMessageQueue

Message= {data: {…}, callbackId: "cb_1_1234"}

where callbackId is the callback function of js. then through

iframe.src='yy://return/_fetchQueue/[{"data":"xxxx","callbackId":"cb_1_4321"}]',

Trigger shouldOverrideUrlLoading method. After java processes the data passed by js, set callback function cb_1_4321 to

Message={responseId: cb_1_4321, responseData:XXX},

This allows callback functions to be handled in js. The specific flow chart is as follows:

JsBridge framework provides two Handler methods, registerHandler method needs to pass in the name of the handler, this requires iOS, Android, H5 three parties to agree on this name, because the business requirements of H5 development change quickly, and H5 calls native methods are also random, so every time you use registerHandler convention name needs to use global variables to store these handler method names is not easy to expand, so in actual development use defaultHanlder, H5 calls native methods when the convention of a cmd, that is, the convention data={cmd: xxx,time:data:{…}}, as long as there is a corresponding function for cmd command in native code, then H5 page can call native methods at any time.

JSBridge improvements suggest that Java calls to js fail occasionally because webview calls to js methods must take effect in the main thread. Also, Js calls to Java occasionally fail because the iframe mechanism does not guarantee that the shouldOverrideUrlLoading callback will be triggered every time.

At present, JSBridge adopts the url scheme. If you do not consider Android 4.2 or below and iOS 7 or below, you can use the interaction, such as injecting a Native object directly into the JS page using addJavaScriptInterface, and changing the previous trigger u step to sending messages to Native using this Native object. This method is only a feasible solution, and the current JSBridge solution basically meets the business requirements in practice.

The above is how the JSBridge framework shared by Xiaobian solves communication problems and realizes mobile cross-platform development. If there are similar doubts, please refer to the above analysis for understanding. If you want to know more about it, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report