目录

Video Adaptation on Web Pages

Overview

Web pages usually contain media resources such as images and videos. When Web components are used to load such pages, video playback adaptation issues may occur. This topic describes the following common web page video adaptation scenarios:

Playing a Video in Full Screen

[h2]When to Use

By default, after the full-screen button of a video is tapped on a web page, the video is played in portrait mode on the mobile device, and the return gesture is not supported. As the video played in portrait mode shows small images, users prefer video playback in landscape mode. In addition, they want to exit the full-screen mode using the return gesture instead of returning to the home screen. In this case, you need to adapt your app to the full-screen mode.

Figure 1 Default effect of playing a video in full screen

[h2]How to Implement

Figure 2 Adaptation process of playing a video in full-screen mode on the web page

To play a video in full-screen mode, the web page needs to be displayed in immersive mode to ensure that the video can be displayed in the non-safe area. For details, see Immersive Effect Development.

To avoid displaying the video in portrait mode after the full-screen is enabled, you need to use the setPreferredOrientation() API to set the screen to landscape mode in the onFullScreenEnter() event callback.

To ensure that the screen remains in portrait mode after the full-screen mode is exited, you need to use the setPreferredOrientation() API to set the screen to portrait mode in the onFullScreenExit() callback.

It should be noted that the logic for triggering exit from the full screen mode by using a return gesture should be supported. Specifically, the callback that triggers the return gesture should first determine whether the current app is in full screen mode. If yes, exit from the full screen mode is triggered. You can trigger the return gesture callback in any of the following ways:

Figure 3 Effect of playing a video in full screen after adaptation

[h2]How to Implement

Entering the Full-Screen Mode

  1. Content in the non-safe area is avoided during web page implementation. When using the Web component to load a web page, you can use expandSafeArea() to expand the safe area to achieve immersive video display.
    Web({
      src: $rawfile(/zh/.test(this.language) ? 'index_cn.html' : 'index_en.html'),
      controller: this.webController
    })
    // ...
      .expandSafeArea([SafeAreaType.SYSTEM])
  2. Customize a function that changes the screen orientation. You can use the setPreferredOrientation() API in the changeOrientation() function to change the screen orientation.
    @Entry
    @Component
    struct Index {
      // ...
      private windowClass: window.Window | null = null;
      private context: common.UIAbilityContext = context as common.UIAbilityContext;
      // ...
      aboutToAppear(): void {
        window.getLastWindow(this.context).then((windowClass) => this.windowClass = windowClass);
        // ...
      }
    
      /**
       * Changes the preferred orientation of the window.
       *
       * @param orientation - The preferred orientation to set. This should be a value from the `window.Orientation` enum.
       * @returns void - This function does not return any value.
       */
      changeOrientation(orientation: window.Orientation) {
        this.windowClass?.setPreferredOrientation(orientation);
      }
    
      // ...
    
      build() {
        // ...
    }
  3. In the onFullScreenEnter() method of the Web component, use the changeOrientation() method to set the screen orientation to window.Orientation.LANDSCAPE. In this case, you need to store handler of the event, which stores the exitFullScreen() method.
    @Entry
    @Component
    struct Index {
      // ...
      private isFullScreen: boolean = false;
      private handler: FullScreenExitHandler | null = null;
      // ...
    
      build() {
        Column() {
          Web({
            src: $rawfile(/zh/.test(this.language) ? 'index_cn.html' : 'index_en.html'),
            controller: this.webController
          })
          // ...
            .onFullScreenEnter((event) => {
              this.handler = event.handler;
              this.changeOrientation(window.Orientation.LANDSCAPE);
              this.isFullScreen = true;
            })
            // ...
    
        }
      }
    }

Exiting the Full-Screen Mode

  1. In the onFullScreenExit() callback of the Web component, call the changeOrientation() method to set the screen orientation to window.Orientation.PORTRAIT.
    Web({
      src: $rawfile(/zh/.test(this.language) ? 'index_cn.html' : 'index_en.html'),
      controller: this.webController
    })
    // ...
      .onFullScreenExit(() => {
        this.changeOrientation(window.Orientation.PORTRAIT);
        this.isFullScreen = false;
      })
  2. Set the return gesture callback. For example, check whether the page is in full-screen mode in onBackPress(). If yes, call exitFullScreen() in the stored handler to exit the full-screen mode.
    onBackPress(): boolean | void {
      if (this.isFullScreen && this.handler) {
        this.handler.exitFullScreen();
        return true;
      }
      return false;
    }

Long-Pressing to Copy a Video Link

[h2]When to Use

Long-pressing to copy a video link is often applied to social sharing. When a user views an interested video in an app and wants to share it, the user can touch and hold the video and select Copy video link to quickly and accurately obtain the video URL.

Figure 4 Effect diagram

[h2]How to Implement

The implementation of this function involves two key steps:

[h2]How to Develop

  1. Define the Menu component as the pop-up window content, and generate the menu list by cyclically rendering the menus data.
    //src/main/ets/view/CustomPopupMenu.ets
    
    /**
     * A custom popup menu Builder.
     *
     * @param uri - The URI for which the popup menu will be built.
     * @param context - The UI context in which the popup menu will be used. This should be an instance of `common.UIAbilityContext`.
     * @param openDownloadDialog - A function that, when called, will open a download dialog.
     * @param closeDownloadDialog - A function that, when called, will close the download dialog.
     * @param changeIsShow - A function that, when called, will change the visibility of certain UI elements.
     */
    @Builder
    export function customPopupMenuBuilder(
      uri: string,
      context: common.UIAbilityContext,
      openDownloadDialog: Function,
      closeDownloadDialog: Function,
      changeIsShow: Function
    ) {
      Column() {
        Menu() {
          ForEach(menus, (menu: MenuItem) => {
            MenuItem({
              content: menu.text
            })
              .height(singlePopupHeight)
              .onClick(() => {
                try {
                  menu.caller && menu.caller(uri, context, openDownloadDialog, closeDownloadDialog);
                  changeIsShow();
                } catch (e) {
                  hilog.error(0x000, Constants.TAG, `some error happened, ${JSON.stringify(e)}`);
                }
              })
          }, (menu: MenuItem) => menu.id)
        }
        .width(popupWidth)
      }
    }
  2. Define isShow as the state variable that controls the pop-up window display, and bind the pop-up window to the Web component.
    const uiContext: UIContext | undefined = AppStorage.get('uiContext');
    let context = uiContext!.getHostContext();
    @Entry
    @Component
    struct Index {
      @State isShow: boolean = false;
      // ...
    
      build() {
        Column() {
          Web({
            src: $rawfile(/zh/.test(this.language) ? 'index_cn.html' : 'index_en.html'),
            controller: this.webController
          })
          // ...
            .bindPopup(this.isShow, {
              builder: customPopupMenuBuilder(
                this.linkUrl,
                this.context,
                this.openDownloadDialog,
                this.closeDownloadDialog,
                this.changeIsShow,
              ),
              enableArrow: false,
              placement: Placement.TopLeft,
              offset: getOffset(this.webWidth, this.webHeight,
                this.pressPosX, this.pressPosY),
              onStateChange: (e) => {
                if (!e.isVisible) {
                  this.isShow = false;
                  this.result?.closeContextMenu();
                }
              }
            })
            // ...
    
        }
      }
    }
  3. In the onContextMenuShow() event of the Web component, use the event.param.getSourceUrl() parameter to obtain the web video URL when a custom pop-up window is triggered.
    @Entry
    @Component
    struct Index {
      @State isShow: boolean = false;
      // ...
    
      build() {
        Column() {
          Web({
            src: $rawfile(/zh/.test(this.language) ? 'index_cn.html' : 'index_en.html'),
            controller: this.webController
          })
          // ...
            .onContextMenuShow((event) => {
              if (!event) {
                return false;
              }
              // ...
              this.linkUrl = event.param.getSourceUrl();
              this.isShow = true;
              return true;
            })
            // ...
    
        }
      }
    }
  4. Use the setData() method to write the obtained link to the system clipboard.
    /**
     * Copies a URI to the system clipboard.
     *
     * @param uri - The URI to be copied to the clipboard. This should be a valid string representing a URI.
     * @returns void - This function does not return any value.
     */
    export function copyLink(uri: string) {
      const pasteData = pasteboard.createData('text/plain', uri);
      pasteboard.getSystemPasteboard().setData(pasteData, (err) => {
        if (err) {
          hilog.error(0x000, Constants.TAG, JSON.stringify(err));
          return;
        }
        context1.showToast({
          message: $r('app.string.copy_success')
        })
      })
    }

Long-Pressing to Download a Video

[h2]When to Use

The function of long-pressing to download a video enables users to save interested videos. Specifically, a user can long-press the video to open a pop-up window and select Download video to save the video to the local device. The downloaded video can also be shared through social sharing channels.

[h2]How to Implement

Figure 5 Adaptation process

After a user long-presses the video area, the video URL can be obtained through the event.param.getSourceUrl() parameter in the onContextMenuShow() API.

For details, see Downloading Files. You can bind the WebDownloadDelegate class to control the download and detect the download status. This class uses the following four callback registration methods to notify the download status:

Call startDownload() through WebviewController associated with the Web component and pass the video link URL to trigger the download.

Figure 6 Effect diagram

[h2]How to Develop

  1. In onContextMenuShow() of the Web component, use event.param.getSourceUrl() in event to obtain the video URL.
    @Entry
    @Component
    struct Index {
      @State isShow: boolean = false;
      // ...
    
      build() {
        Column() {
          Web({
            src: $rawfile(/zh/.test(this.language) ? 'index_cn.html' : 'index_en.html'),
            controller: this.webController
          })
          // ...
            .onContextMenuShow((event) => {
              if (!event) {
                return false;
              }
              // ...
              this.linkUrl = event.param.getSourceUrl();
              this.isShow = true;
              return true;
            })
            // ...
    
        }
      }
    }
  2. Use setDownloadDelegate() to bind WebDownloadDelegate to WebviewController associated with the Web component.
    export class WebDownloadManager extends AbstractWebDownloadManager
    implements ControllerManager {
      // ...
      // Define the download delegate instance.
      private delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate();
    
      // ...
      public start(controllerName: string, path: string, url: string): Promise<string> {
        return new Promise((resolve, reject) => {
          const controller = this.getController(controllerName);
          // ...
            // Associate the download delegate with the webview controller.
            controller?.setDownloadDelegate(this.delegate);
            // ...
          } catch (error) {
            hilog.error(0x0000, 'testTag', 'Execution failed, code = %{public}d, message = %{public}s',
              error.code, error.message);
          }
        });
      }
    
      // ...
    }
  3. Set event callbacks for the WebDownloadDelegate class.
    1. Specify the file path before the download. You can use filesDir of UIAbilityContent to pass the application sandbox as the download path and use the start() method of WebDownloadItem to pass the download path.
      this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => {
        this.currentTask = webDownloadItem;
        this.sourcePath = path + '/' + webDownloadItem.getSuggestedFileName();
        this.currentTask.start(this.sourcePath);
        // Specify the download path before downloading.
        this.taskStatus = webDownloadItem.getState();
      })
    2. During the download, maintain the download information as required. For example, you can maintain downloadProgress and downloadSpeed for the UI component to display. The download progress is obtained through the getPercentComplete() method invoked by webDownloadItem, and the download speed is obtained through the getCurrentSpeed() method invoked by webDownloadItem.
      this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => {
        this.currentTask = webDownloadItem;
        // maintain download progress.
        this.downloadProgress = webDownloadItem.getPercentComplete();
        this.downloadSpeed = webDownloadItem.getCurrentSpeed();
        this.taskStatus = webDownloadItem.getState();
      })
    3. After the download is successful, prompt a message indicating that the download is complete, and subsequent service logics can be executed as needed. For example, share a video to other apps or save the video to another location. In this example, a message is displayed indicating that the download is complete.
      this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => {
        this.taskStatus = webDownloadItem.getState();
        resolve(this.sourcePath);
      })
    4. WebDownloadDelegate also provides the callback used when the download fails and the serialize() method, which can be used to serialize failed download tasks for subsequent download resumption.
      this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => {
        // Serialize the download data when the download fails to resume the download.
        this.failedData = webDownloadItem.serialize();
        this.taskStatus = webDownloadItem.getState();
        reject(new Error('download failed'));
      })
    5. Use the setDownloadDelegate() method of webview.WebDownloadManager to rebind the WebDownloadDelegate class at a proper time, use the deserialize() method to deserialize the failed data, and use the resumeDownload() method to resume the download task. The resumed task automatically starts to download data.
      // Provides an external interface for resuming downloads.
      public resume() {
        const state = this.currentTask.getState();
        if (state === webview.WebDownloadState.CANCELED) {
          webview.WebDownloadManager.setDownloadDelegate(this.delegate);
          try {
            webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData));
          } catch (error) {
            hilog.error(0x0000, 'testTag', 'Execution failed, code = %{public}d, message = %{public}s',
              error.code, error.message);
          }
        }
      }
  4. Use the startDownload() method of WebviewController to pass the obtained video link to start the download.
    controller?.startDownload(url);

Summary

This topic describes the adaptation practices of web page videos, including avoiding displaying videos in portrait mode by default during full-screen playback, obtaining video links and writing them to the clipboard, and downloading web page videos using the Web components, you can adapt web page videos as required.

Sample Code