Home  >  Article  >  Web Front-end  >  Introduction to common data interaction methods between JavaScript and native applications

Introduction to common data interaction methods between JavaScript and native applications

不言
不言forward
2018-11-12 17:16:132271browse

This article brings you an introduction to commonly used data interaction methods between JavaScript and native applications. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Scenario 1

H5 pages are often used in native apps, such as event pages in e-commerce, detail pages in some e-commerce, etc. ...These pages all have one characteristic, that is, the possibility of modification in the future, and the chance of one-time modification is particularly high. Therefore, using H5 pages is the wisest choice.
Once you use H5, you will inevitably have some interactions with native development (Android, IOS). The following solutions can help you solve it.
The implementation principle is to inject a js method into the js window object natively, so that the native application can trigger the penalty. It is as simple as our usual method of calling onclick.

js code:

// mobile/index.js 常用js 调用原生的方式都在这里体现。
export default {
    /**
     * 调用移动端方法
     *
     * @param {*} {name, params, call} 移动端注入的方法名 | 参数 | 回调
     */
    callMoblieMethods({name, params, call}){
        // 移动端安卓的环境
        if(window.android) {
            // 移动端使用java所以不能直接解析json,只能解析字符串或者json字符串
            window.android[name](JSON.stringify(params));  
        }
        // 移动端IOS的环境
        if(window.webkit && window.webkit.messageHandlers) {
            window.webkit.messageHandlers[name].postMessage(params);
        }
    }
}

Calling method

if(window.android || (window.webkit && window.webkit.messageHandlers.activityDetails)) {
    mobile.callMoblieMethods({ name: 'activityDetails', params: {activityId: item.act_id}});
}

This judgment condition may seem strange to you. I have tested various machine models, and the Android machine window is definitely There is no attribute, but on IOS it will have its own webkit attribute, so we first determine whether it has a webkit attribute and then determine whether it has an injected method name so that it can call this method well;

In order to facilitate your search, the mobile code is also attached here:

//Android

public class AndroidJavascriptInterface {

  Activity mActivity;

  public AndroidJavascriptInterface(Activity activity) {
      this.mActivity = activity;
  }

  //诊所详情
  @JavascriptInterface
  public void clinicDetails(String jsonData) {
      Log.i("znh", "H5-JS-诊所详情");
      Intent intent = new Intent(mActivity, OutPatientActivity.class);
      Bundle bundle = new Bundle();
      bundle.putString(Constants.CLINIC_ID, GsonUtil.getJSONObjectKeyVal(jsonData, "clinicId"));
      intent.putExtras(bundle);
      mActivity.startActivity(intent);
  }

  //活动详情
  @JavascriptInterface
  public void activityDetails(String jsonData) {
      Log.i("znh", "H5-JS-活动详情");
      Intent intent = new Intent(mActivity, ActivityDetailActivity.class);
      Bundle bundle = new Bundle();
      bundle.putString("id", GsonUtil.getJSONObjectKeyVal(jsonData, "activityId"));
      intent.putExtras(bundle);
      mActivity.startActivity(intent);
  }
}


//IOS
#import <JavaScriptCore/JavaScriptCore.h>

WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
[wkWebConfig.userContentController addScriptMessageHandler:self name:@"clinicDetails"];
[wkWebConfig.userContentController addScriptMessageHandler:self name:@"activityDetails"];

Through this process, you can easily call the native method.

Scenario 2

We need to use a link in the text message to open the native application. If there is no such link, he will be prompted to download an application. First, the native application You need to define a url link for front-end programmers to call in the browser. Let me show you a link example first:

// IOS
iOSStarClinic://

// Andriod 
yjjkyl://starclinic

Short and concise, you only need to call this

Then in js What to do?

if(this.isIOS) {
    window.location.href = 'iOSStarClinic://';//与APP约定的一个协议URL
} else {
    var state = null;
    try {
        state = window.open('yjjkyl://starclinic', '_blank');//与APP约定的一个协议URL
    } catch(e) {}
    if (state) {
        window.close();
    } else {
        window.location.href = gbs.patientDownUrl;
    }
}

First determine whether the current environment is IOS or Android. In fact, current browsers can no longer use folk remedies (timing methods) to check whether the application is installed at the current time, because the browser will pop up a prompt box for the user Confirmation is required to jump, so once the user does not click to confirm, the browser will jump! Therefore, some content should be displayed to the user on the current page so that there are other business processes when the user does not open the application.

The above is the detailed content of Introduction to common data interaction methods between JavaScript and native applications. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete