All Products
Search
Document Center

Mobile Platform as a Service:HTML5 container extension

Last Updated:Feb 02, 2023

HTML5 container provides rich extension capabilities, and to make it easier for users to use HTML5 containers in more scenarios, this topic introduces the following HTML5 container extensions with examples.

H5Plugin obtaining Activity result

In many scenes, such as facial recognition and code recognition, you need to start a new Activity to get the result returned by the Activity. But in such a scenario, JSAPI cannot directly get the result by rewriting H5Activity. Thus, when using the HTML5 container, you need to get the result returned by the Activity in the following way:

  1. In the custom H5Plugin, register OnH5ActivityResult callback. Code sample is as follows:

    H5ActivityResultManager.getInstance().put(onH5ActivityResult);
    Note
    • put method doesn’t check for duplicate registrations, developers need to prevent duplicate registrations themselves.

    • After regestration, you need to call the remove method to remove the callback. Normally, it is recommended that you remove the callback in the onRelease method of H5Plugin. Code sample is as follows:

    H5ActivityResultManager.getInstance().remove(onH5ActivityResult);
  2. Start the target Activity using startActivityForResult method, for example, you can start the activity in the custom H5Plugin handleEvent method. Code sample is as follows:

    public boolean handleEvent(H5Event event, H5BridgeContext context) {
     if ("CustomJSAPI".equals(event.getAction())) {
         if (event.getActivity()!=null){
             Intent intent = new Intent(event.getActivity(), yourDestinationActivity.class);
             event.getActivity().startActivityForResult(intent,requestCode,bundle);
         }
         return true;
     }
     return false;
    }
    Note

    This method is only used to call back the result of H5Activity.

  3. In the callback method of OnH5ActivityResult, pass the result to the front end via H5BridgeContext object.

    public interface OnH5ActivityResult {
         void onGetResult(int requestCode, int resultCode, Intent intent);
    }

Customize HTML5 error page

When you need to customize the HTML5 error page, the steps are as follows:

  1. Create a custom error page in HTML format.

     <!doctype html>
     <html lang="zh-cn">
    
     <head>
       <meta charset="utf-8" />
       <meta name="viewport" content="width=device-width,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
       <meta name="format-detection" content="telephone=no" />
       <title>Custom error</title>
     </head>
    
     <body>
         <p>This is a custom error page</p>
     </body>
    
     </html>
  2. Implement H5ErrorPageView. Set the error page you just created in APWebView.

     public class H5ErrorPageViewImpl implements H5ErrorPageView {
         @Override
         public boolean enableShowErrorPage() {
             // True indicates launching the custom error page.
             return true;
         }
         @Override
         public void errorPageCallback(H5Page h5Page, APWebView view, String errorUrl, int statusCode, String errorMsg, String subErrorMsg) {
             // Obtain the html of the error page. In this demo, it is put into raw, but you can also put it in another place.
             String html = H5ResourceManager.readRawFromResource(R.raw.custom_error, LauncherApplicationAgent.getInstance().getApplicationContext().getResources());
             // Set the error page in webview
             view.loadDataWithBaseURL(errorUrl, html, "text/html", "utf-8", errorUrl);
         }
     }
  3. Register H5ErrorPageView. Before opening the HTML5 container, register the custom H5ErrorPageView in the container.

    H5Utils.setProvider(H5ErrorPageView.class.getName(),new H5ErrorPageViewImpl());
    Note

    mPaaS baseline 10.1.68.7 and above supports the new MPH5ErrorPageView method, which is consistent with H5ErrorPageView in the aspects of method name and usage, but the parameters are extended.

/**
 * Interface for customizing network error page 
 */
public interface MPH5ErrorPageView {
    /**
     * @param h5Page      page object
     * @param view        webview object
     * @param errorUrl    error URL
     * @param statusCode  error code
     * @param errorMsg    error description
     * @param subErrorMsg sub error description
     * @param extInfo     extended information,you need to check if it is empty 
     * @param extObj      extended class,you need to check if it is empty
     * @return true indicates custom page is required,and errorPageCallback method below will be used 
     */
    boolean enableShowErrorPage(H5Page h5Page, APWebView view, String errorUrl, int statusCode, String errorMsg, String subErrorMsg, Bundle extInfo, Object extObj);
    /**
     * @param h5Page      page object
     * @param view        webview object
     * @param errorUrl    error URL
     * @param statusCode  error code
     * @param errorMsg    error description
     * @param subErrorMsg sub error description
     * @param extInfo     extended information,you need to check if it is empty
     * @param extObj      extended class,you need to check if it is empty
     */
    void errorPageCallback(H5Page h5Page, APWebView view, String errorUrl, int statusCode, String errorMsg, String subErrorMsg, Bundle extInfo, Object extObj);
}

Enable translucent status bar

Note

  • This function is only supported in mPaaS baseline 10.1.60 and above.

  • This method sets the status bar color of all HTML5 pages opened by the HTML5 container. If you have more requirements on status bar color, you can implement the HTML5 container Custom title bar.

  • You can choose to set the status bar color in openTranslucentStatusBarSupport method of container title bar interface, or handle it in other places.

  1. Enable TSBS in HTML5 container configuration.

  2. If you use built-in title bar, developers can implement H5TransStatusBarColorProvider interface, and set the instance in HTML5 container via H5Utils.setProvider method. Code sample is as follows:

     package com.mpaas.demo.nebula;
    
     import android.graphics.Color;
    
     import com.alipay.mobile.nebula.provider.H5TransStatusBarColorProvider;
    
     public class H5TransStatusBarColorProviderImpl implements H5TransStatusBarColorProvider {
         @Override
         public int getColor() {
             return Color.argb(70, 255, 255, 255);
         }
     }

Add third-party JavaScriptInterface

Many third-party pages require JavaScriptInterface. You can implement it in the following steps:

  1. Implement plug-in to intercept the loading event of the third-party page.

  2. Obtain WebView and inject JavaScript object.

Code sample:

package com.mpaas.demo.nebula;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.mobile.h5container.api.H5BridgeContext;
import com.alipay.mobile.h5container.api.H5Event;
import com.alipay.mobile.h5container.api.H5EventFilter;
import com.alipay.mobile.h5container.api.H5Param;
import com.alipay.mobile.h5container.api.H5SimplePlugin;

public class TechFinSitePlugin extends H5SimplePlugin {

    @Override
    public void onPrepare(H5EventFilter filter) {
        super.onPrepare(filter);
        filter.addAction(CommonEvents.H5_PAGE_SHOULD_LOAD_URL);
    }

    @Override
    public boolean interceptEvent(H5Event event, H5BridgeContext context) {
        String action = event.getAction();
        if (CommonEvents.H5_PAGE_SHOULD_LOAD_URL.equals(action)) {
            JSONObject params = event.getParam();
            String url = params.getString(H5Param.LONG_URL);
            if (!TextUtils.isEmpty(url) && url.contains("tech.antfin.com")) {
                event.getH5page().getWebView().addJavascriptInterface(new TechFinJavaScriptInterface(), "techFinBridge");
            }
        }

        return false;
    }
}
Note

Do not return true in the interceptEvent method, otherwise the loading page of the container may be compromised.

package com.mpaas.demo.nebula;

import android.webkit.JavascriptInterface;

public class TechFinJavaScriptInterface {

    @JavascriptInterface
    @com.uc.webview.export.JavascriptInterface
    public String whoAmI() {
        return "It is tech fin.";
    }
}
Note

The annotation classes used in System core and UC core are different, you must make it compatible with these two annotation classes.

Add cutscene in HTML5 container

To add a cutscene to an HTML5 container, you only need to add the animation resources to the project’s res/anim folder. The steps are as follows:

  1. Create an anim folder under the project’s res folder. Skip this step if it already exists.

  2. Add the resource files of the animation to the anim folder. The HTML5 container automatically recognizes resource files based on their file names, so the file names for resource files can only be h5_slide_out_right.xml, h5_slide_out_left.xml, h5_slide_in_right.xml, or h5_slide_in_left.xml. You can refer to the following example to create your own resource file.

    • h5_slide_out_right.xml

      <?xml version="1.0" encoding="utf-8"?>
      <set xmlns:android="http://schemas.android.com/apk/res/android">
      <translate
        android:fromXDelta="0%"
        android:toXDelta="100%"
        android:duration="300" />
      </set>
    • h5_slide_out_left.xml

      <?xml version="1.0" encoding="utf-8"?>
      <set xmlns:android="http://schemas.android.com/apk/res/android">
      <translate
        android:fromXDelta="0%"
        android:toXDelta="-100%"
        android:duration="300" />
      </set>
    • h5_slide_in_right.xml

      <?xml version="1.0" encoding="utf-8"?>
      <set xmlns:android="http://schemas.android.com/apk/res/android">
      <translate
        android:fromXDelta="100%"
        android:toXDelta="0"
        android:duration="300" />
      </set>
    • h5_slide_in_left.xml

      <?xml version="1.0" encoding="utf-8"?>
      <set xmlns:android="http://schemas.android.com/apk/res/android">
      <translate
        android:fromXDelta="-100%"
        android:toXDelta="0%"
        android:duration="300" />
      </set>

Configure the blacklist for the JSAPI of the H5 Container

Configure a blacklist for JSAPI to control the specified domain name’s calling authority to JSAPI. The steps are as follows:

  1. Inherit the H5JSApiPermissionProvider class and override the hasDomainPermission method. The two input parameters of the hasDomainPermission method are action and url. action represents the event name of the custom JSAPI, and url represents the sign of the current page. The return value is of type boolean. true means that the event can be processed, and false means that the event is not authorized to be processed. The demo is as follows, for reference only.

    public class H5JSApiPermissionProviderImpl implements H5JSApiPermissionProvider {
         private static final List blackList = new ArrayList<String>();
         static {
         // URLs in the blacklist don't have authority to execute JSAPI or other related events.
         blackList.add("https://mcube-prod.cn-hangzhou.oss.aliyuncs.com/ONEX4B905F1032156-MUAT/20210728/0.0.0.1_all/nebula/fallback/www/index.html");
         }
    
         @override
         public boolean hasDomainPermission(String action, String url) {
             // The accessor can judge whether he has the authority to execute the current action according to the action name and url.
             // The action is the defined JSAPI event, return true means that it can handle the event, return false means that it is not authorized to handle the event.
             if (blackList.contains(url)) {
                 return false;
             }
             return true;
         }
         @override
         public boolean hasThisPermission(String permission, String url) {
             return true;
         }
    }
  2. Set the Provider after the initialization of the framework is completed.

    H5Utils.setProvider(H5JSApiPermissionProvider.class.getName(), new H5JSApiPermissionProviderImpl());