目录

Web组件同层渲染时如何传自定义参数

问题现象

在Web组件同层渲染场景下,H5中的object标签如何传自定义参数并通过onNativeEmbedLifecycleChange回调接收参数?

背景知识

解决方案

object标签支持param/value的自定义属性传值,使用时需要将enableNativeEmbedMode属性设置为true,调用registerNativeEmbedRule注册同层渲染的HTML标签名和类型,最后通过onNativeEmbedLifecycleChange回调中获取到自定义属性值。

应用侧示例代码如下:

import { webview } from '@kit.ArkWeb';

@Entry
@Component
struct WebRender {
  controller: webview.WebviewController = new webview.WebviewController();

  build() {
    Column() {
      Web({ src: $rawfile('render.html'), controller: this.controller })
        .domStorageAccess(true)
        .fileAccess(true)
        .geolocationAccess(false)
        .enableNativeEmbedMode(true)
        .registerNativeEmbedRule('object', 'test/input')
        .onNativeEmbedLifecycleChange((event) => {
          if (event.info) {
            console.info('NativeEmbedParams: ' + event.info.params?.['testName']);
          }
        });
    };
  }
}

HTML示例代码如下:

<!--src/main/resources/rawfile/render.html-->
<!DOCTYPE html>
<html>
<head>
    <title>同层渲染html</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background:white">
<object id = "input1" type="test/input" style="width: 300px; height: 100px">
    <param name="testName" value="testValue">
</object>
</body>
</html>

打印结果如下图: