文档管理中心
您当前正在浏览新版开发者文档中心,目录分类和层级有所调整。点击左侧当前文档分类名称前的“☰”图标,可切换文档分类。 了解新版目录
最佳实践功能开发应用框架ArkWebArkWeb渲染框架适配

ArkWeb渲染框架适配

概述

Hybrid应用开发是介于Web应用和系统应用两者之间的应用开发技术,兼具“系统应用良好交互体验”的优势和“Web应用跨平台开发”的优势。其主要原理是由Native通过JSBridge通道提供统一的API,然后用Html/CSS实现界面,JS来写业务逻辑,能够调用系统API,最终的页面在WebView中显示。

Hybrid应用鸿蒙化方案

整体架构

  1. Ark进程:由ArkTS引擎提供运行时,具备调用系统API的能力。应用启动从Ark进程进入,完成EntryAbility的初始化并创建HarmonyOS应用页面。Ark进程可以动态或者静态创建Webview运行时环境,并加载html/css/js资源文件。
  2. Webview进程:默认支持标准W3C API,对ArkTS侧资源的访问有限制。Webview渲染能力主要由Web组件提供。用户可以通过Web组件的属性配置是否开启同层渲染能力、是否允许执行JavaScript脚本等。
  3. JSBridge:上述两种进程的通讯机制,允许数据双向流动。Webview进程通过JSBridge通道访问拓展API。

方案设计

Hybrid应用鸿蒙化方案主要集中在双端通信JSBridge实现、拓展接口实现和基于同层渲染的原生组件实现。JSBridge是前端与ArkTS进行双向通信的桥梁。通过JSBridge,前端应用能访问到ArkTS侧实现的拓展接口,实现更丰富的业务功能。视图层方面,可以使用系统提供的同层渲染能力,把部分性能要求比较高的前端组件改成ArkTS实现,以达到更好的体验效果。下图蓝色背景的方框图展示了上述三点所处的框架位置:

业务实现中的关键点

Hybrid应用鸿蒙化方案主要围绕双端通信、API鸿蒙化、组件鸿蒙化三方面进行开发。双端通信:JS侧使用ArkTS的通道,是鸿蒙化的基石;API鸿蒙化:针对JS侧平台相关的API,提供一套HarmonyOS版本的实现;组件鸿蒙化:针对Web组件,以同层渲染的方式提供替代组件,以提升组件的性能与交互体验。

双端通信

JSBridge扮演Webview进程与ArkUI主进程沟通的桥梁,是一种双向通信的机制。HarmonyOS系统提供Web组件以及@ohos.web.webview等ArkWeb API来进行Web开发。可以通过WebMessagePort以及javaScriptProxy代理的方式实现JSBridge。

  1. WebMessagePort是一种比较基础的消息发送以及接收机制,支持的消息类型为string和ArrayBuffer,具体业务消息内容的封装和解析需要从零设计,存在上手难、工作量大的特点。
  2. JavaScriptProxy代理机制注入ArkUI主进程对象(如命名为native)到Webview中,在Webview的window上生成对应代理对象,业务可以直接调用该代理对象的方法,相关的操作将作用到ArkUI主进程的native对象。代码实例如下:
    收起
    自动换行
    深色代码主题
    复制
    1. // Web component loading H5.
    2. Web({ src: this.param.path, controller: this.webController })
    3. .zoomAccess(false)
    4. .width(Const.WEB_CONSTANT_WIDTH)
    5. .aspectRatio(1)
    6. .margin({
    7. left: Const.WEB_CONSTANT_MARGIN_LEFT, right: Const.WEB_CONSTANT_MARGIN_RIGHT,
    8. top: Const.WEB_CONSTANT_MARGIN_TOP
    9. })
    10. .onErrorReceive((event) => {
    11. if (event?.error.getErrorInfo() === 'ERR_INTERNET_DISCONNECTED') {
    12. this.getUIContext().getPromptAction().showToast({
    13. message: $r('app.string.internet_err'),
    14. duration: Const.WEB_CONSTANT_DURATION
    15. });
    16. }
    17. if (event?.error.getErrorInfo() === 'ERR_CONNECTION_TIMED_OUT') {
    18. this.getUIContext().getPromptAction().showToast({
    19. message: $r('app.string.internet_err'),
    20. duration: Const.WEB_CONSTANT_DURATION
    21. });
    22. }
    23. })
    24. .onProgressChange((event) => {
    25. if (event?.newProgress === Const.WEB_CONSTANT_PROGRESS_MAX) {
    26. this.isLoading = false;
    27. clearInterval(this.intervalLoading);
    28. this.intervalLoading = -1;
    29. }
    30. })
    31. .javaScriptProxy({
    32. object: this.linkObj,
    33. name: 'linkObj',
    34. methodList: ['messageFromHtml'],
    35. controller: this.webController
    36. })

前端可以使用native.makePhoneCall(..) 的方式进行调用。且方法的参数支持基本类型、字典对象、函数等,对于JSBridge的设计提供了便利。关于Web.javaScriptProxy()以及WebviewController.registerJavaScriptProxy()的使用方法可以参考《前端页面调用应用侧函数》。

通过对比,javaScriptProxy注入对象的方式构造JSBridge是一个比较好的技术选型。建议JSBridge的实现基于注入机制进行设计,并考虑分层设计来提高其通用性和灵活性,下图展示一种分层设计思路:

  1. 通信层:对上层屏蔽具体的通信机制,主要负责Web侧和ArkTS侧数据的传递,但不解析数据的业务含义,不关注传递的数据内容。数据可以序列化为字符串进行传递或者以object对象进行传递。使用javaScriptProxy代理机制实现的通信层代码示例如下:
    收起
    自动换行
    深色代码主题
    复制
    1. // Web component loading H5.
    2. Web({ src: this.param.path, controller: this.webController })
    3. .zoomAccess(false)
    4. .width(Const.WEB_CONSTANT_WIDTH)
    5. .aspectRatio(1)
    6. .margin({
    7. left: Const.WEB_CONSTANT_MARGIN_LEFT, right: Const.WEB_CONSTANT_MARGIN_RIGHT,
    8. top: Const.WEB_CONSTANT_MARGIN_TOP
    9. })
    10. .onErrorReceive((event) => {
    11. if (event?.error.getErrorInfo() === 'ERR_INTERNET_DISCONNECTED') {
    12. this.getUIContext().getPromptAction().showToast({
    13. message: $r('app.string.internet_err'),
    14. duration: Const.WEB_CONSTANT_DURATION
    15. });
    16. }
    17. if (event?.error.getErrorInfo() === 'ERR_CONNECTION_TIMED_OUT') {
    18. this.getUIContext().getPromptAction().showToast({
    19. message: $r('app.string.internet_err'),
    20. duration: Const.WEB_CONSTANT_DURATION
    21. });
    22. }
    23. })
    24. .onProgressChange((event) => {
    25. if (event?.newProgress === Const.WEB_CONSTANT_PROGRESS_MAX) {
    26. this.isLoading = false;
    27. clearInterval(this.intervalLoading);
    28. this.intervalLoading = -1;
    29. }
    30. })
    31. .javaScriptProxy({
    32. object: this.linkObj,
    33. name: 'linkObj',
    34. methodList: ['messageFromHtml'],
    35. controller: this.webController
    36. })
  2. 通道层(Channel):允许注册多种方法层通道。该层的JS侧实现负责把方法层的API信息对象(包含名称、参数、返回值类型等信息)打包成通信层识别的信息数据,交给通信层传递到ArkTS侧。ArkTS侧的实现包含两个主要功能,一个是把信息数据解包出API的信息,并交给ArkTS侧的方法层调用具体的API;另外一个功能就是执行jsCall,ArkTS侧通过WebviewController .runJavaScript()方法在执行JS侧的回调函数。

    在JS侧,nativeCall()方法提供打包转换能力。如下面示例:

    收起
    自动换行
    深色代码主题
    复制
    1. function openDialog() {
    2. linkObj.messageFromHtml(prizesArr[prizesPosition]);
    3. }

    在ArkTS侧,通过runJavaScript()执行JS侧方法:

    收起
    自动换行
    深色代码主题
    复制
    1. Button($r('app.string.btnValue'))
    2. .fontSize(Const.WEB_CONSTANT_BUTTON_FONT_SIZE)
    3. .fontColor($r('app.color.start_window_background'))
    4. .margin({ top: Const.WEB_CONSTANT_BUTTON_MARGIN_TOP })
    5. .width(Const.WEB_CONSTANT_BUTTON_WIDTH)
    6. .height(Const.WEB_CONSTANT_BUTTON_HEIGHT)
    7. .backgroundColor($r('app.color.blue'))
    8. .borderRadius(Const.WEB_CONSTANT_BUTTON_BORDER_RADIUS)
    9. .onClick(() => {
    10. this.webController.runJavaScript('startDraw()');
    11. })
  3. 方法层(MethodChannel):可以针对一类API格式封装成一种MethodChannel。同种MethodChannel的API具备一致的参数规范、返回值规范,比如小程序API规范,这样便于把API的调用信息封装成结构化的信息对象,供给通道层进行传递。

JSBridge的设计是否合理关系到应用的性能,开发者也可以考虑是否需要批量缓存请求再统一发送请求来减少请求次数,或者把不变的请求结果进行缓存等等。

API鸿蒙化

H5业务设计中除了使用W3C API外,还可以使用ArkTS侧API拓展来访问设备。如下图所示:

系统高阶API是对系统API的一层封装,实现更符合业务要求的接口。拓展API的规范设计具有较大的灵活性,建议对API的参数,返回值类型格式进行限制,使用基本类型或者简单的字典对象,尽量避免使用复杂的类型的参数或返回值,可以参考比较成熟的小程序框架,其规范格式可以分成三种类型:

  1. func(paramObj), 其中 paramObj包含基本类型的数据属性以及success/fail/complete()回调函数。
  2. on/offFunc(callback), 注册和移除监听函数。
  3. getXxManager(): obj, 获取某类功能的全局单例管理器,如文件管理器。管理器的方法也遵守上述两点规范。

设计过程中可以把API都汇聚到一个对象作为属性字段存在,方便在切面视角增加统一的参数、返回值加工处理,拦截处理。示意图如下:

组件鸿蒙化

HarmonyOS提供同层渲染能力把原生组件直接渲染到WebView层级,从而获得更大的灵活性以及性能上获得更好表现。开发者可通过Web组件同层渲染相关属性来进行控制:enableNativeEmbedMode开关控制;onNativeEmbedLifecycleChange处理同层渲染生命周期:CREATE/UPDATE/DESTROY;onNativeEmbedGestureEvent处理交互事件。同层渲染功能要求前端页面文件中显式使用embed标签,并且embed标签内type必须以“native/”开头。使用Vue等框架可以方便地进一步封装embed标签生成自定义组件,并增加更多属性、事件和方法,通过JSBridge与ArkTS侧进行同步。在ArkTS侧,对应地需要自定义实现一个原生组件或者使用系统内置组件,通过NodeContainer组件进行动态挂载。同层渲染的原理如下:

开发角度:前端页面开发者使用<embed>标签来表示使用原生组件;应用开发者使用NodeContainer关联离屏节点树,使用makeNode()接口在H5页面上渲染出组件。

离屏节点动态上下树:

1)开发者初始构建一个NodeContainer对象表示一个空的占位符。NodeContainer里面内容为空时,在初始化的时候大小为0,不参与布局。

2)NodeController持有buildnode对象,通过makeNode()接口将buildnode对象返回给NodeContainer,来实现动态上树。

3) NodeController里面rebuild()方法,触发NodeContainer重新调用makeNode()接口。 makeNode()接口若返回空,则实现动态下树。

使用H5结合embed标签示例:

收起
自动换行
深色代码主题
复制
  1. <div>
  2. <div id="bodyId">
  3. <embed id="nativeSearch" type = "native/component" width="100%" height="100%" src="view"/>
  4. </div>
  5. </div>

在ArkTS侧,可以扩展NodeController来统一管理同层渲染节点。其makeNode()接口实现示例如下:

收起
自动换行
深色代码主题
复制
  1. import { PRODUCT_DATA } from '../viewmodel/GoodsViewModel';
  2. import { ProductDataModel } from '../model/GoodsModel';
  3. import { BuilderNode, FrameNode, NodeController, NodeRenderType } from '@kit.ArkUI';
  4. import { webview } from '@kit.ArkWeb';
  5. // Margin vertical
  6. const MARGIN_VERTICAL: number = 8;
  7. // Font weight
  8. const FONT_WEIGHT: number = 500;
  9. // Placeholder
  10. const PLACEHOLDER: ResourceStr = $r('app.string.embed_search');
  11. declare class Params {
  12. width: number;
  13. height: number;
  14. }
  15. declare class NodeControllerParams {
  16. surfaceId: string;
  17. type: string;
  18. renderType: NodeRenderType;
  19. embedId: string;
  20. width: number;
  21. height: number;
  22. }
  23. class SearchNodeController extends NodeController {
  24. private rootNode: BuilderNode<[Params]> | undefined | null = null;
  25. private embedId: string = "";
  26. private surfaceId: string = "";
  27. private renderType: NodeRenderType = NodeRenderType.RENDER_TYPE_DISPLAY;
  28. private componentWidth: number = 0;
  29. private componentHeight: number = 0;
  30. private componentType: string = "";
  31. /**
  32. * 设置渲染参数
  33. *
  34. * @param params 渲染参数
  35. */
  36. setRenderOption(params: NodeControllerParams): void {
  37. this.surfaceId = params.surfaceId;
  38. this.renderType = params.renderType;
  39. this.embedId = params.embedId;
  40. this.componentWidth = params.width;
  41. this.componentHeight = params.height;
  42. this.componentType = params.type;
  43. }
  44. /**
  45. * 创建节点
  46. *
  47. * @param uiContext UIContext
  48. * @returns 节点
  49. */
  50. makeNode(uiContext: UIContext): FrameNode | null {
  51. this.rootNode = new BuilderNode(uiContext, { surfaceId: this.surfaceId, type: this.renderType });
  52. if (this.componentType === 'native/component') {
  53. this.rootNode.build(wrapBuilder(searchBuilder), { width: this.componentWidth, height: this.componentHeight });
  54. }
  55. return this.rootNode.getFrameNode();
  56. }
  57. setBuilderNode(rootNode: BuilderNode<Params[]> | null): void {
  58. this.rootNode = rootNode;
  59. }
  60. getBuilderNode(): BuilderNode<[Params]> | undefined | null {
  61. return this.rootNode;
  62. }
  63. updateNode(arg: Object): void {
  64. this.rootNode?.update(arg);
  65. }
  66. getEmbedId(): string {
  67. return this.embedId;
  68. }
  69. postEvent(event: TouchEvent | undefined): boolean {
  70. return this.rootNode?.postTouchEvent(event) as boolean;
  71. }
  72. }
  73. @Component
  74. struct SearchComponent {
  75. @Prop params: Params;
  76. controller: SearchController = new SearchController()
  77. build() {
  78. Column({ space: MARGIN_VERTICAL }) {
  79. Text($r("app.string.embed_mall"))
  80. .fontSize($r('app.string.ohos_id_text_size_body4'))
  81. .fontWeight(FONT_WEIGHT)
  82. .fontFamily('HarmonyHeiTi-Medium')
  83. Row() {
  84. Search({ placeholder: PLACEHOLDER, controller: this.controller })
  85. .backgroundColor(Color.White)
  86. }
  87. .width($r("app.string.embed_full_percent"))
  88. .margin($r("app.integer.embed_row_margin"))
  89. Grid() {
  90. ForEach(PRODUCT_DATA, (item: ProductDataModel, index: number) => {
  91. GridItem() {
  92. Column({ space: MARGIN_VERTICAL }) {
  93. Image(item.imageRes).width($r("app.integer.embed_image_size"))
  94. Row({ space: MARGIN_VERTICAL }) {
  95. Text(item.title)
  96. .fontSize($r('app.string.ohos_id_text_size_body1'))
  97. .width(100)
  98. .maxLines(1)
  99. .textOverflow({ overflow: TextOverflow.Ellipsis })
  100. Text(item.price)
  101. .fontSize($r('app.string.ohos_id_text_size_body1'))
  102. .width(50)
  103. .maxLines(1)
  104. }
  105. }
  106. .backgroundColor($r('app.color.ohos_id_color_background'))
  107. .alignItems(HorizontalAlign.Center)
  108. .justifyContent(FlexAlign.Center)
  109. .width($r("app.string.embed_full_percent"))
  110. .height($r("app.string.embed_full_percent"))
  111. .borderRadius($r('app.string.ohos_id_corner_radius_default_m'))
  112. }
  113. }, (item: ProductDataModel, index: number) => index.toString())
  114. }
  115. .columnsTemplate('1fr 1fr')
  116. .rowsTemplate('1fr 1fr 1fr')
  117. .rowsGap($r('app.string.ohos_id_elements_margin_vertical_m'))
  118. .columnsGap($r('app.string.ohos_id_elements_margin_vertical_m'))
  119. .width($r("app.string.embed_full_percent"))
  120. .height($r("app.string.embed_sixty_percent"))
  121. .backgroundColor($r('app.color.ohos_id_color_sub_background'))
  122. }
  123. .padding($r('app.string.ohos_id_card_margin_start'))
  124. .width(this.params.width)
  125. .height(this.params.height)
  126. }
  127. }
  128. @Builder
  129. function searchBuilder(params: Params) {
  130. SearchComponent({ params: params })
  131. .backgroundColor($r('app.color.ohos_id_color_sub_background'))
  132. }
  133. @Entry
  134. @Component
  135. struct Index {
  136. browserTabController: WebviewController = new webview.WebviewController();
  137. @State componentIdArr: Array<string> = [];
  138. private nodeControllerMap: Map<string, SearchNodeController> = new Map();
  139. build() {
  140. Stack() {
  141. ForEach(this.componentIdArr, (componentId: string) => {
  142. NodeContainer(this.nodeControllerMap.get(componentId));
  143. }, (embedId: string) => embedId)
  144. Web({ src: $rawfile("embed_view.html"), controller: this.browserTabController })
  145. .backgroundColor($r('app.color.ohos_id_color_sub_background'))
  146. .zoomAccess(false)
  147. .enableNativeEmbedMode(true)
  148. .onNativeEmbedLifecycleChange((embed) => {
  149. const componentId = embed.info?.id?.toString() as string
  150. if (embed.status === NativeEmbedStatus.CREATE) {
  151. let nodeController = new SearchNodeController();
  152. nodeController.setRenderOption({
  153. surfaceId: embed.surfaceId as string,
  154. type: embed.info?.type as string,
  155. renderType: NodeRenderType.RENDER_TYPE_TEXTURE,
  156. embedId: embed.embedId as string,
  157. width: this.getUIContext().px2vp(embed.info?.width),
  158. height: this.getUIContext().px2vp(embed.info?.height)
  159. });
  160. nodeController.rebuild();
  161. this.nodeControllerMap.set(componentId, nodeController);
  162. this.componentIdArr.push(componentId);
  163. } else if (embed.status === NativeEmbedStatus.UPDATE) {
  164. let nodeController = this.nodeControllerMap.get(componentId);
  165. nodeController?.updateNode({
  166. text: 'update',
  167. width: this.getUIContext().px2vp(embed.info?.width),
  168. height: this.getUIContext().px2vp(embed.info?.height)
  169. } as ESObject);
  170. nodeController?.rebuild();
  171. } else {
  172. let nodeController = this.nodeControllerMap.get(componentId);
  173. nodeController?.setBuilderNode(null);
  174. nodeController?.rebuild();
  175. }
  176. })
  177. .onNativeEmbedGestureEvent((touch) => {
  178. this.componentIdArr.forEach((componentId: string) => {
  179. let nodeController = this.nodeControllerMap.get(componentId);
  180. if (nodeController?.getEmbedId() === touch.embedId) {
  181. nodeController?.postEvent(touch.touchEvent);
  182. }
  183. })
  184. })
  185. }
  186. }
  187. }

实现中可以使用map容器把embedType和离屏节点的builder()函数进行关联,当makeNode()执行时,取出embedType对应的builder()函数来创建rootNode节点,最后把rootNode节点关联的FrameNode返回,达到离屏节点动态上树、H5渲染出原生组件的效果。同层渲染可以参考文档《同层渲染绘制Video和Button组件》