All Products
Search
Document Center

HTML5 container extension

Last Updated: Aug 16, 2021

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 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:

       
    1. 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:

       
    1. 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:

       
    1. public boolean handleEvent(H5Event event, H5BridgeContext context) {
    2. if ("CustomJSAPI".equals(event.getAction())) {
    3. if (event.getActivity()!=null){
    4. Intent intent = new Intent(event.getActivity(), yourDestinationActivity.class);
    5. event.getActivity().startActivityForResult(intent,requestCode,bundle);
    6. }
    7. return true;
    8. }
    9. return false;
    10. }
    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.

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

Customize HTML5 error page

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

  1. Create a custom error page in HTML format.

       
    1. <!doctype html>
    2. <html lang="zh-cn">
    3. <head>
    4. <meta charset="utf-8" />
    5. <meta name="viewport" content="width=device-width,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
    6. <meta name="format-detection" content="telephone=no" />
    7. <title>Custom error</title>
    8. </head>
    9. <body>
    10. <p>This is a custom error page</p>
    11. </body>
    12. </html>
  2. Implement H5ErrorPageView. Set the error page you just created in APWebView.
       
    1. public class H5ErrorPageViewImpl implements H5ErrorPageView {
    2. @Override
    3. public boolean enableShowErrorPage() {
    4. // True indicates launching the custom error page.
    5. return true;
    6. }
    7. @Override
    8. public void errorPageCallback(H5Page h5Page, APWebView view, String errorUrl, int statusCode, String errorMsg, String subErrorMsg) {
    9. // Obtain the html of the error page. In this demo, it is put into raw, but you can also put it in another place.
    10. String html = H5ResourceManager.readRawFromResource(R.raw.custom_error, LauncherApplicationAgent.getInstance().getApplicationContext().getResources());
    11. // Set the error page in webview
    12. view.loadDataWithBaseURL(errorUrl, html, "text/html", "utf-8", errorUrl);
    13. }
    14. }
  3. Register H5ErrorPageView. Before opening HTML5 container, register the custom H5ErrorPageView in container.
       
    1. 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 aspects of method name and usage, but the parameters are extended.

 
  1. /**
  2. * Interface for customizing network error page
  3. */
  4. public interface MPH5ErrorPageView {
  5. /**
  6. * @param h5Page page object
  7. * @param view webview object
  8. * @param errorUrl error URL
  9. * @param statusCode error code
  10. * @param errorMsg error description
  11. * @param subErrorMsg sub error description
  12. * @param extInfo extended information,you need to check if it is empty
  13. * @param extObj extended class,you need to check if it is empty
  14. * @return true indicates custom page is required,and errorPageCallback method below will be used
  15. */
  16. boolean enableShowErrorPage(H5Page h5Page, APWebView view, String errorUrl, int statusCode, String errorMsg, String subErrorMsg, Bundle extInfo, Object extObj);
  17. /**
  18. * @param h5Page page object
  19. * @param view webview object
  20. * @param errorUrl error URL
  21. * @param statusCode error code
  22. * @param errorMsg error description
  23. * @param subErrorMsg sub error description
  24. * @param extInfo extended information,you need to check if it is empty
  25. * @param extObj extended class,you need to check if it is empty
  26. */
  27. void errorPageCallback(H5Page h5Page, APWebView view, String errorUrl, int statusCode, String errorMsg, String subErrorMsg, Bundle extInfo, Object extObj);
  28. }

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 HTML5 container. If you have more requirements on status bar color, you can implement 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:

       
    1. package com.mpaas.demo.nebula;
    2. import android.graphics.Color;
    3. import com.alipay.mobile.nebula.provider.H5TransStatusBarColorProvider;
    4. public class H5TransStatusBarColorProviderImpl implements H5TransStatusBarColorProvider {
    5. @Override
    6. public int getColor() {
    7. return Color.argb(70, 255, 255, 255);
    8. }
    9. }

Add third-party JavaScriptInterface

Many third-party pages requires 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:

 
  1. package com.mpaas.demo.nebula;
  2. import android.text.TextUtils;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alipay.mobile.h5container.api.H5BridgeContext;
  5. import com.alipay.mobile.h5container.api.H5Event;
  6. import com.alipay.mobile.h5container.api.H5EventFilter;
  7. import com.alipay.mobile.h5container.api.H5Param;
  8. import com.alipay.mobile.h5container.api.H5SimplePlugin;
  9. public class TechFinSitePlugin extends H5SimplePlugin {
  10. @Override
  11. public void onPrepare(H5EventFilter filter) {
  12. super.onPrepare(filter);
  13. filter.addAction(CommonEvents.H5_PAGE_SHOULD_LOAD_URL);
  14. }
  15. @Override
  16. public boolean interceptEvent(H5Event event, H5BridgeContext context) {
  17. String action = event.getAction();
  18. if (CommonEvents.H5_PAGE_SHOULD_LOAD_URL.equals(action)) {
  19. JSONObject params = event.getParam();
  20. String url = params.getString(H5Param.LONG_URL);
  21. if (!TextUtils.isEmpty(url) && url.contains("tech.antfin.com")) {
  22. event.getH5page().getWebView().addJavascriptInterface(new TechFinJavaScriptInterface(), "techFinBridge");
  23. }
  24. }
  25. return false;
  26. }
  27. }
Note: Do not return “ture” in the interceptEvent method, otherwise the loading page of the container may be compromised.
 
  1. package com.mpaas.demo.nebula;
  2. import android.webkit.JavascriptInterface;
  3. public class TechFinJavaScriptInterface {
  4. @JavascriptInterface
  5. @com.uc.webview.export.JavascriptInterface
  6. public String whoAmI() {
  7. return "It is tech fin.";
  8. }
  9. }
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
           
      1. <?xml version="1.0" encoding="utf-8"?>
      2. <set xmlns:android="http://schemas.android.com/apk/res/android">
      3. <translate
      4. android:fromXDelta="0%"
      5. android:toXDelta="100%"
      6. android:duration="300" />
      7. </set>
    • h5_slide_out_left.xml
           
      1. <?xml version="1.0" encoding="utf-8"?>
      2. <set xmlns:android="http://schemas.android.com/apk/res/android">
      3. <translate
      4. android:fromXDelta="0%"
      5. android:toXDelta="-100%"
      6. android:duration="300" />
      7. </set>
    • h5_slide_in_right.xml
           
      1. <?xml version="1.0" encoding="utf-8"?>
      2. <set xmlns:android="http://schemas.android.com/apk/res/android">
      3. <translate
      4. android:fromXDelta="100%"
      5. android:toXDelta="0"
      6. android:duration="300" />
      7. </set>
    • h5_slide_in_left.xml
           
      1. <?xml version="1.0" encoding="utf-8"?>
      2. <set xmlns:android="http://schemas.android.com/apk/res/android">
      3. <translate
      4. android:fromXDelta="-100%"
      5. android:toXDelta="0%"
      6. android:duration="300" />
      7. </set>

Configure the whitelist for the JSAPI of the H5 Container

Configure a whitelist 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.

       
    1. public class H5JSApiPermissionProviderImpl implements H5JSApiPermissionProvider {
    2. private static final List whiteList = new ArrayList<String>();
    3. static {
    4. // URLs in the whitelist don't have authority to execute JSAPI or other related events.
    5. whiteList.add("https://mcube-prod.cn-hangzhou.oss.aliyuncs.com/ONEX4B905F1032156-MUAT/20210728/0.0.0.1_all/nebula/fallback/www/index.html");
    6. }
    7. @override
    8. public boolean hasDomainPermission(String action, String url) {
    9. // The accessor can judge whether he has the authority to execute the current action according to the action name and url.
    10. // 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.
    11. if (whiteList.contains(url)) {
    12. return false;
    13. }
    14. return true;
    15. }
    16. @override
    17. public boolean hasThisPermission(String permission, String url) {
    18. return true;
    19. }
    20. }
  2. Set the Provider after the initialization of the framework is completed.
       
    1. H5Utils.setProvider(H5JSApiPermissionProvider.class.getName(), new H5JSApiPermissionProviderImpl());