preface

If this is your first time working with an app to develop webView pages, you probably don’t know enough about how to debug and what the problems are. This article tries to give you an entry level understanding based on their own experience, if it is the big guy level, you can detour.

Webview protocol

In order to better develop in the app debug our mobile page (h5), we need some basic agreement with app developers principle, to ensure that our page can be a very good debugging, including debugging tools, flexible simulation online app environment, test questions in the process of interaction and convenient custom modifications for the h5 address, etc.

The following schemes are for reference only, and each one is of practical use. If the webview in the company needs accurate debugging and follow-up development, it is necessary to consider the following problems.

The theme plan note
Unified UA identification For example, add [XXX] at the end of ua. There is no
H5 common app header The APP end provides a unified APP header, referring to the UA interaction of Alipay and wechat, and provides simple operations to display page title, return and close. The default page can be scrolled Later, other H5 will be in this class browser shell by default. For some fixed layout schemes of the front end, this shell needs to be optimized and perfected. If the time of the front end technical transformation allows, it is best to provide a complete and determined scheme which can be seamlessly connected and displayed in webView
H5 with APP custom header Specific headers are provided for specific product and interaction requirements, such as single-page, strongly interactive logic pages The product needs to specify the specificity, not the browser return, such as return need to add a confirmation box, you need to customize
Functional interaction between H5 and APP Agree the format of conventional interaction methods, and give some fixed and available methods for mutual communication, such as obtaining user information and obtaining APP network status This is a two-way functional interaction. Some methods of H5 can also set app state, page jump, data storage, etc
Pure interactive method between H5 and APP Retrieve the corresponding app loading box, loading failure, photo album control, scan code control Need to interact with the product to determine whether to use app native controls or H5 effects.
The sharing and communication between H5 and APP in different scenarios For example: Users in different apps: APP shares the H5 detail page, and the H5 detail page can also be opened in app Need convention rules
The app provides a webView shell You can enter the Webview scene through the app shell scanning code to simulate interaction and solve some problems in the APP during the development stage The above app solutions are integrated into this app shell

About the communication between WEbiEW and H5 in app

As we know, generally webView pages include two cases, one is originally limited to the H5 page that only APP will embed, this part of the communication with app, we are more by jsBridge. One is plain H5 pages.

JsBridge put it more directly, that is, when a web page is loaded, it will inject a specified JS file into the page, and then there will be a method known to both the front end and the app. Through this method, the front end can call up the interactive controls of the APP, or even jump to other app pages. You can also know some device status, network status and user information of the app at this time. The APP can also know the status of the page through H5, and then do the desired operation when necessary.

On the other hand, WebView can also be seen as an ordinary browser, which can load any page, so our non-app embedded H5 can also be opened in app through webView. The H5 outside the APP can evoke the APP through the app’s self-defined protocol code.

The relevant communication technology points can be seen in the crude illustration below.

JsBridge Reference documentation

Interaction Between iOS and H5 (iOS)

IOS interacts with H5 in JavaScriptCore mode. When the WebView loads a URL, iOS will manually bind a JSContext object to the H5 page. Using this JSContext object, two-way interaction between OC and JS can be achieved. Note: The JSContext object is bound in the iOS webViewDidFinishLoad: callback, and no interaction with the OC can be used until the binding is complete.

JS calls the OC interface

Before JS starts calling the OC interface, there are several prerequisites:

  • Js’s window.isReady method has already been triggered before it can call a method provided by OC. The reason is that iOS will call the isReady method to the JS side only after the JSContext is bound successfully. Therefore, JS can call the OC method through JSContext only after isReady is triggered.

  • IOS binds JSContext objects to a specified field, and OC registers native methods to this field in the Page Window object. Such as window. The app.

  • If the js side wants to receive the result of the native method asynchronously, it needs to define the callback method in the global scope

JS sample code:

Js calls OC native method to synchronously obtain user basic information

// Specify that the interface to get user information is registered with the app property of the window
The getUserInfo method is a synchronous method that can be retrieved directly by the js side
// The object returned can be a JSON string
var info = window.app.getUserInfo()
Copy the code

Js calls the OC native method, takes photos and uploads the job picture, and asynchronously obtains the upload result

// Assume that the OC interface associated with the job is registered with the Window homework property
window.homework.uploadHomeworkPicture(questionID)

// The callback method is defined in the global scope to receive the return value
// The native method calls this callback indirectly after uploading the picture
function homeworkPictureDidUploaded(questionID, picUrl) {
  	// do something...
}
Copy the code

Call the generic native interface in JS:

@param productId Commodity ID(string type) */
app.gotoCourseDetail(productId);

/** Close the current page */
app.finish();

/** Gets user information, returned as a JSON string. The main parameters are as follows: memberId: user ID Token: user login unique ID memberType: user type */
app.getUserInfo();

/** @param MSG (string) */
app.toast(msg);

/** Display dialog @param title title (string string) @param MSG message (string string) @param Actions Click event (a JSON array string), each array element field is as follows: title: Event title (string string, such as "cancel") callback: JS callback method of the event (string string) Example: var Actions = "[{'title': 'cancel ', 'callback': 'cancelPay'}, {' title ':' sure, 'callback' : 'confirmPay}]." App. confirm(" Tips ", "Do you want to pay the order?" , actions); * /
app.confirm(title, msg, actions);
Copy the code

OC calls the JS interface

OC notes when calling JS methods:

  • The js method should be declared in the global scope, otherwise OC will not get the method

  • If you call the js method directly from webViewDidFinishLoad: with JSContext, you may get an invalid call request. To avoid such problems, it is recommended to call the JS method in setTimeout mode

Sample code:

OC calls js’s isReady method in webViewDidFinishLoad:

JSValue *isReadyFunc = self.jsContext[@"isReady"]; if (isReadyFunc) { [self.jsContext[@"setTimeout"] callWithArguments:@[isReadyFunc, @100]]; }Copy the code

OC calls JS’s setUserInfo method in the native method that JS initiates

// JavaScriptCore supports NSDictionary and NSArray as arguments to the js method NSDictionary *userInfo =... ; [self.jsContext[@"setUserInfo"] callWithArguments:@[userInfo]];Copy the code

JS provides a generic interface definition for native calls:

/** This method is called after iOS native initialization to tell JS that it is ready */ 
function isReady();

/** * return Boolean Type return value: true h5 already processes the return, native does not process; False H5 does not process the return, native directly returns the parent native page */
function gobackIfNeeded();
Copy the code

Wake up the APP

Define scheme: com. XXX. App

UserAgent

The default WebView UserAgent is “XXXX XXX/1.3.0”, where XXXX is the default system UserAgent. “/” is followed by the app version number

H5 embedded page loading (Android)

1. Natively provide a frame page to the H5 page. The framework provides only one class called InnerWeb (which JS doesn’t need to know about). To load a pure H5 embedded page locally, use the IntentHelper. StartWeb (Context Context, String URL) method to load an embedded H5 page. The inside is just loading this URL. The rest of the logic is handled by H5.

Android natively invokes JavaScript methods in HTML pages via Java

There are two types of native calling JS methods:

  1. Method with no return value
  2. There are return value methods

Call a method with no return value in js

Very simple, we can directly call the specific code example is as follows:

/** * f1 is a function declared in js */
mWebView.loadUrl("javascript:f1()");
Copy the code

Now you can call the js method.

Call a method that has a return value in js

A little more complicated, as follows:

/** * sum is the function defined in js */
mWebView.evaluateJavascript("The sum (1, 2)".new ValueCallback<String>() {
        @Override
        public void onReceiveValue(String value) {
            Log.e(TAG, "onReceiveValue value="+ value); }});Copy the code

Js calls Android native Java methods

The mapping object that is provided locally for js calls, which requires injection, we also use an object called app. Js to call a local method. All start with that to represent our native methods.

Details are as follows:

<script type="text/javascript"> function s(){var result = window.app.gotologin (); document.getElementById("p").innerHTML = result; } </script>Copy the code

The local code is as follows:

public calss AppJavascriptInterface {

  	@JavascriptInterface
  	public void gotoLogin(a) {
        if (mContext.get() == null) {
            Log.w("web"."Page closed");
            return; } LoginActivity.start(mContext.get()); }}Copy the code

Product agreement

The agreement is mainly provided to H5 in its original form. Here is my detailed list:

/** * jump to login */
@JavascriptInterface
public void gotoLogin(a);
/** * Jump course details */
@JavascriptInterface
public void gotoCourseDetail(a);
/** * close the current page */
@JavascriptInterface
public void finish(a);
** The following information is returned to H5 in JSON format: * memberId: user ID * Token: unique id of user login * memberType: user type */
@JavascriptInterface
public String getUserInfo(a);

/** * Returned ** The following information is returned to H5 in JSON format: * memberId: user ID * Token: user login unique id * memberType: user type */
public void back(a);

/ * * * * /
public void toast(String msg);

public void confirm(String title, String msg, String positiveFunctionName, String negativeFunctionName);
Copy the code
/** * return Boolean Type return value: true h5 already processes the return, native does not process; False H5 does not process returns, native returns the last non-H5 page */
function gobackIfNeeded();

Copy the code

Wake up scheme of APP:

1. Define Scheme: com.xxx.app

2. The opening of the specific page is to be determined

Ua: “XXXX XXX/1.3.0″, where XXXX is the default UA. IOS is different from Android.” /” indicates the app version number

H5 arouse the app

H5 evoking APP has become one of the indispensable functions at present. As one of the necessary technology stacks in the front-end technology stack, we need to know how to arouse APP in the non-APP environment and correctly identify whether the system has app installed.

System related

The application name URL Scheme
SMS sms://
app store itms-apps://
The phone tel://
Wireless LAN App-Prefs:root=WIFI
bluetooth App-Prefs:root=Bluetooth
Cellular mobile network App-Prefs:root=MOBILE_DATA_SETTINGS_ID
Personal hotspot App-Prefs:root=INTERNET_TETHERING
Operator, App-Prefs:root=Carrier
notice App-Prefs:root=NOTIFICATIONS_ID
general App-Prefs:root=General
Universal – About the machine App-Prefs:root=General&path=About
General purpose keyboard App-Prefs:root=General&path=Keyboard
General purpose – Auxiliary functions App-Prefs:root=General&path=ACCESSIBILITY
Universal – Language and region App-Prefs:root=General&path=INTERNATIONAL
General-reduction App-Prefs:root=Reset
The wallpaper App-Prefs:root=Wallpaper
Siri App-Prefs:root=SIRI
privacy App-Prefs:root=Privacy
Safari App-Prefs:root=SAFARI
music App-Prefs:root=MUSIC
Music – Equalizer App-Prefs:root=MUSIC&path=com.apple.Music:EQ
Photos and Cameras App-Prefs:root=Photos
FaceTime App-Prefs:root=FACETIME

application

The application name URL Scheme
weibo weibo://
QQ mqq://
QQ group mqqapi://card/show_pslcard? Src_type = internal&version = 1 & card_type = group&uin = {QQ group no.}
QQ contact mqqapi://card/show_pslcard? Src_type = internal&version = 1 & uin = {} QQ number
Alipay alipay://
WeChat weixin://
WeChat wechat://
Wechat – Scan weixin://dl/scan
Wechat – Feedback weixin://dl/feedback
Wechat – Moments of friends weixin://dl/moments
Wechat – Settings weixin://dl/settings
Wechat – Message notification Settings weixin://dl/notifications
Wechat – Chat Settings weixin://dl/chat
Wechat – Universal Settings weixin://dl/general
Wechat – public account weixin://dl/officialaccounts
Wechat – Games weixin://dl/games
Wechat – Help weixin://dl/help
Wechat – Personal information weixin://dl/profile
Wechat – function plug-in weixin://dl/features
Dried shrimp music xiami://
chrome googlechrome://
Weibo International edition weibointernational://
The worship the bike mobike://
ofo ofoapp://
Youdao Cloud Note youdaonote://
Impression of notes evernote://
Today’s headline snssdk141://
Netease news newsapp://
Netease Cloud Music orpheuswidget://
QQ music qqmusic://
QQ Music recently played qqmusic://today? mid=31&k1=2&k4=0
Meituan take-away meituanwaimai://
Meituan imeituan://
Gmail googlegmail://
Netease mail neteasemail://
QQ email qqmail://
Tencent video tenvideo://
iQIYI iqiyi://
12306 cn.12306://
Youdao dictionary yddict://
nailing dingtalk://

Refer to the article

  • H5 evokes app guide
  • Commonly used the URL Scheme