文档管理中心

属性

本文导读
展开章节

通用属性仅支持aspectRatiobackdropBlurbackgroundColorbindContentCoverbindContextMenubindMenu bindSheetborderColorborderRadiusborderStyleborderWidthclipconstraintSizedefaultFocusfocusabletabIndexgroupDefaultFocusdisplayPriorityenabledflexBasisflexShrinklayoutWeightidgridOffsetgridSpanuseSizeTypeheighttouchablemarginmarkAnchoroffsetwidthzIndexvisibilityscaletranslateresponseRegionsizeopacityshadowsharedTransitiontransitionpositiondirection

说明
  • 该组件从API version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。

  • 示例效果请以真机运行为准。

概述

PhonePC/2in1TabletTVWearable

Web组件属性用于在ArkUI声明式语法下以链式调用的方式配置Web组件的网页加载行为、安全策略、运行环境与交互能力,是定制Web组件行为的主要入口。其中通用的样式与布局类属性(如尺寸、边距、背景、可见性等)请参考尺寸设置,本章仅描述Web组件特有的属性;运行期动态控制类能力(如加载URL、前进后退、注册/反注册JS对象、运行JavaScript、注入CSS等)请配合WebviewController使用。

domStorageAccess

PhonePC/2in1TabletTVWearable

domStorageAccess(domStorageAccess: boolean)

设置是否开启文档对象模型存储接口(DOM Storage API)权限,当属性没有显式调用时,默认不开启文档对象模型存储接口(DOM Storage API)权限。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
domStorageAccess boolean

设置是否开启文档对象模型存储接口(DOM Storage API)权限。

true表示开启文档对象模型存储接口权限,false表示不开启文档对象模型存储接口权限。

传入undefined或null时为false。

说明
  • 网页中使用到文档对象模型存储接口(DOM Storage API),需将其设置为true,才可正常加载网页。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .domStorageAccess(true)
  11. }
  12. }
  13. }

fileAccess

PhonePC/2in1TabletTVWearable

fileAccess(fileAccess: boolean)

设置是否开启应用中文件系统的访问。$rawfile(filepath/filename)中的文件不受该属性影响而被限制访问。API version 11及以前,当属性没有显式调用时,默认开启应用中文件系统的访问。API version 12及以后,当属性没有显式调用时,默认不开启应用中文件系统的访问。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
fileAccess boolean

设置是否开启应用中文件系统的访问。

true表示开启应用中文件系统的访问。false表示不开启应用中文件系统的访问。

同时,当fileAccess为false的时候,仅只读资源目录/data/storage/el1/bundle/entry/resources/resfile里面的资源依然可以通过file协议访问,不受fileAccess管控。

API version 11及以前,传入undefined或null时为true,API version 12及以后传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .fileAccess(true)
  11. }
  12. }
  13. }

imageAccess

PhonePC/2in1TabletTVWearable

imageAccess(imageAccess: boolean)

设置是否允许自动加载图片资源。当属性没有显式调用时,允许自动加载图片资源。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
imageAccess boolean

设置是否允许自动加载图片资源。

true表示设置允许自动加载图片资源,false表示设置不允许自动加载图片资源。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .imageAccess(true)
  11. }
  12. }
  13. }

javaScriptProxy

PhonePC/2in1TabletTVWearable

javaScriptProxy(javaScriptProxy: JavaScriptProxy)

将javaScriptProxy中的ArkTS对象注册到Web组件中,该对象将使用JavaScriptProxy中指定的名称注册到网页的所有框架中,包括所有iframe,这使得JavaScript可以调用javaScriptProxy中ArkTS对象的方法。当属性没有显式调用时,默认不将javaScriptProxy中的ArkTS对象注册到Web组件中。

说明

javaScriptProxy接口需要和deleteJavaScriptRegister9+接口配合使用,防止内存泄漏。

javaScriptProxy对象的所有参数不支持更新。

注册javaScriptProxy对象时,同步与异步列表请至少选择一项不为空,可同时注册两类方法。

此接口只支持注册一个对象,若需要注册多个对象请使用registerJavaScriptProxy9+

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
javaScriptProxy JavaScriptProxy

参与注册的对象。只能声明方法,不能声明属性。

传入undefined或null时不将javaScriptProxy中的ArkTS对象注册到Web组件中。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. import { BusinessError } from '@kit.BasicServicesKit';
  4. class TestObj {
  5. constructor() {
  6. }
  7. test(data1: string, data2: string, data3: string): string {
  8. console.info("data1:" + data1);
  9. console.info("data2:" + data2);
  10. console.info("data3:" + data3);
  11. return "AceString";
  12. }
  13. asyncTest(data: string): void {
  14. console.info("async data:" + data);
  15. }
  16. toString(): void {
  17. console.info('toString' + "interface instead.");
  18. }
  19. }
  20. @Entry
  21. @Component
  22. struct WebComponent {
  23. controller: webview.WebviewController = new webview.WebviewController();
  24. testObj = new TestObj();
  25. build() {
  26. Column() {
  27. Button('deleteJavaScriptRegister')
  28. .onClick(() => {
  29. try {
  30. this.controller.deleteJavaScriptRegister("objName");
  31. } catch (error) {
  32. console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
  33. }
  34. })
  35. Web({ src: 'www.example.com', controller: this.controller })
  36. .javaScriptAccess(true)
  37. .javaScriptProxy({
  38. object: this.testObj,
  39. name: "objName",
  40. methodList: ["test", "toString"],
  41. asyncMethodList: ["asyncTest"],
  42. controller: this.controller,
  43. })
  44. }
  45. }
  46. }

javaScriptAccess

PhonePC/2in1TabletTVWearable

javaScriptAccess(javaScriptAccess: boolean)

设置是否允许执行JavaScript脚本。当属性没有显式调用时,默认允许执行JavaScript脚本。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
javaScriptAccess boolean

是否允许执行JavaScript脚本。

true表示允许执行JavaScript脚本,false表示不允许执行JavaScript脚本。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .javaScriptAccess(true)
  11. }
  12. }
  13. }

overScrollMode11+

PhonePC/2in1TabletTVWearable

overScrollMode(mode: OverScrollMode)

设置Web过滚动模式。开启时,用户在Web根页面滑动到边缘会触发弹性动画弹回界面,但根页面上的内部页面不会触发回弹。该属性没有显式调用时,默认关闭过滚动模式。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
mode OverScrollMode

设置Web的过滚动模式为关闭或开启。

传入undefined或null时为OverScrollMode.NEVER。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State mode: OverScrollMode = OverScrollMode.ALWAYS;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .overScrollMode(this.mode)
  12. }
  13. }
  14. }

mixedMode

PhonePC/2in1TabletTVWearable

mixedMode(mixedMode: MixedMode)

设定当安全源尝试从非安全源加载资源时的行为。当属性没有显式调用时,默认值为MixedMode.None,即禁止安全源从非安全源加载内容。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
mixedMode MixedMode

要设置的混合内容模式。

传入undefined或null时为MixedMode.All。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State mode: MixedMode = MixedMode.All;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .mixedMode(this.mode)
  12. }
  13. }
  14. }

onlineImageAccess

PhonePC/2in1TabletTVWearable

onlineImageAccess(onlineImageAccess: boolean)

设置是否允许从网络加载图片资源(通过HTTP和HTTPS访问的资源)。当属性没有显式调用时,默认允许从网络加载图片资源。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
onlineImageAccess boolean

设置是否允许从网络加载图片资源。

true表示设置允许从网络加载图片资源,false表示设置不允许从网络加载图片资源。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .onlineImageAccess(true)
  11. }
  12. }
  13. }

zoomAccess

PhonePC/2in1TabletTVWearable

zoomAccess(zoomAccess: boolean)

设置是否支持手势进行缩放。该属性没有显式调用时,默认支持手势进行缩放。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
zoomAccess boolean

设置是否支持手势进行缩放。

true表示设置支持手势进行缩放,false表示设置不支持手势进行缩放。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .zoomAccess(true)
  11. }
  12. }
  13. }

overviewModeAccess

PhonePC/2in1TabletTVWearable

overviewModeAccess(overviewModeAccess: boolean)

设置是否使用概览模式加载网页,即缩小内容以适应屏幕宽度。当属性没有显式调用时,默认允许使用概览模式加载网页。

系统能力: SystemCapability.Web.Webview.Core

设备行为差异: 该接口在PC/2in1设备中无效果,在其他设备中可正常调用。

参数:

展开
参数名 类型 必填 说明
overviewModeAccess boolean

设置是否使用概览模式加载网页。

true表示设置使用概览模式加载网页,false表示设置不使用概览模式加载网页。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .overviewModeAccess(true)
  11. }
  12. }
  13. }

databaseAccess

PhonePC/2in1TabletTVWearable

databaseAccess(databaseAccess: boolean)

设置Web SQL数据库存储API权限,若未显式调用,此权限默认关闭。

说明
  • 本接口在ArkWeb内核升级到M132版本后因内核废弃Web SQL,对Web SQL数据库的控制失效。ArkWeb内核版本参考ArkWeb简介约束与限制

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
databaseAccess boolean

设置是否开启Web SQL数据库存储API权限。

true表示开启,false表示关闭。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .databaseAccess(true)
  11. }
  12. }
  13. }

geolocationAccess

PhonePC/2in1TabletTVWearable

geolocationAccess(geolocationAccess: boolean)

设置是否开启获取地理位置权限。当属性没有显式调用时,默认开启。具体使用方式参考管理位置权限

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
geolocationAccess boolean

设置是否开启获取地理位置权限。

true表示开启,false表示不开启。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .geolocationAccess(true)
  11. }
  12. }
  13. }

mediaPlayGestureAccess9+

PhonePC/2in1TabletTVWearable

mediaPlayGestureAccess(access: boolean)

设置有声视频的自动播放是否需要用户手动点击,静音视频播放不受该接口管控。当该属性未显式设置时,默认有声视频的自动播放需要用户手动点击。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
access boolean

设置有声视频的自动播放是否需要用户手动点击。

true表示设置有声视频的自动播放需要用户手动点击,false表示设置有声视频的自动播放不需要用户手动点击,能自动播放。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State access: boolean = true;
  8. build() {
  9. Column() {
  10. Web({ src: $rawfile('index.html'), controller: this.controller })
  11. .mediaPlayGestureAccess(this.access)
  12. }
  13. }
  14. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>视频播放页面</title>
  6. </head>
  7. <body>
  8. <h1>视频播放</h1>
  9. <video id="testVideo" controls autoplay>
  10. // 需要在video标签中配置autoplay属性,允许视频自动播放
  11. // 在resources的rawfile目录放置任意一个mp4媒体文件,并将其命名为example.mp4
  12. <source src="example.mp4" type="video/mp4">
  13. </video>
  14. </body>
  15. </html>

multiWindowAccess9+

PhonePC/2in1TabletTVWearable

multiWindowAccess(multiWindow: boolean)

设置是否开启多窗口权限。当属性没有显式调用时,默认不开启多窗口权限。

使能多窗口权限时,需要实现onWindowNew事件,示例代码参考onWindowNew

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
multiWindow boolean

设置是否开启多窗口权限。

true表示设置开启多窗口权限,false表示设置不开启多窗口权限。

horizontalScrollBarAccess9+

PhonePC/2in1TabletTVWearable

horizontalScrollBarAccess(horizontalScrollBar: boolean)

设置是否显示横向滚动条,包括系统默认滚动条和用户自定义滚动条。该属性没有显式调用时,默认显示横向滚动条。

说明
  • 通过@State变量控制横向滚动条的隐藏/显示后,需要调用controller.refresh()生效。
  • 通过@State变量频繁动态改变时,建议切换开关变量和Web组件一一对应。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
horizontalScrollBar boolean

设置是否显示横向滚动条。

true表示设置显示横向滚动条,false表示设置不显示横向滚动条。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. import { BusinessError } from '@kit.BasicServicesKit';
  4. @Entry
  5. @Component
  6. struct WebComponent {
  7. controller: webview.WebviewController = new webview.WebviewController();
  8. @State isShow: boolean = true;
  9. @State btnMsg: string = '隐藏滚动条';
  10. build() {
  11. Column() {
  12. // 通过@State变量改变横向滚动条的隐藏/显示后,需调用this.controller.refresh()后生效
  13. Button('refresh')
  14. .onClick(() => {
  15. if (this.isShow) {
  16. this.isShow = false;
  17. this.btnMsg = '显示滚动条';
  18. } else {
  19. this.isShow = true;
  20. this.btnMsg = '隐藏滚动条';
  21. }
  22. try {
  23. this.controller.refresh();
  24. } catch (error) {
  25. console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
  26. }
  27. }).height('10%').width('40%')
  28. Web({ src: $rawfile('index.html'), controller: this.controller }).height('90%')
  29. .horizontalScrollBarAccess(this.isShow)
  30. }
  31. }
  32. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta name="viewport" id="viewport" content="width=device-width,initial-scale=1.0">
  6. <title>Demo</title>
  7. <style>
  8. body {
  9. width:3000px;
  10. height:6000px;
  11. padding-right:170px;
  12. padding-left:170px;
  13. border:5px solid blueviolet;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. Scroll Test
  19. </body>
  20. </html>

verticalScrollBarAccess9+

PhonePC/2in1TabletTVWearable

verticalScrollBarAccess(verticalScrollBar: boolean)

设置是否显示纵向滚动条,包括系统默认滚动条和用户自定义滚动条。该属性没有显式调用时,默认显示纵向滚动条。

说明
  • 通过@State变量控制纵向滚动条的隐藏/显示后,需要调用controller.refresh()生效。
  • 通过@State变量频繁动态改变时,建议切换开关变量和Web组件一一对应。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
verticalScrollBar boolean

设置是否显示纵向滚动条。

true表示设置显示纵向滚动条,false表示设置不显示纵向滚动条。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. import { BusinessError } from '@kit.BasicServicesKit';
  4. @Entry
  5. @Component
  6. struct WebComponent {
  7. controller: webview.WebviewController = new webview.WebviewController();
  8. @State isShow: boolean = true;
  9. @State btnMsg: string = '隐藏滚动条';
  10. build() {
  11. Column() {
  12. // 通过@State变量改变纵向滚动条的隐藏/显示后,需调用this.controller.refresh()后生效
  13. Button(this.btnMsg)
  14. .onClick(() => {
  15. if (this.isShow) {
  16. this.isShow = false;
  17. this.btnMsg = '显示滚动条';
  18. } else {
  19. this.isShow = true;
  20. this.btnMsg = '隐藏滚动条';
  21. }
  22. try {
  23. this.controller.refresh();
  24. } catch (error) {
  25. console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
  26. }
  27. }).height('10%').width('40%')
  28. Web({ src: $rawfile('index.html'), controller: this.controller }).height('90%')
  29. .verticalScrollBarAccess(this.isShow)
  30. }
  31. }
  32. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta name="viewport" id="viewport" content="width=device-width,initial-scale=1.0">
  6. <title>Demo</title>
  7. <style>
  8. body {
  9. width:3000px;
  10. height:6000px;
  11. padding-right:170px;
  12. padding-left:170px;
  13. border:5px solid blueviolet;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. Scroll Test
  19. </body>
  20. </html>

cacheMode

PhonePC/2in1TabletTVWearable

cacheMode(cacheMode: CacheMode)

设置缓存模式。当属性没有显式调用时,默认为CacheMode.Default。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
cacheMode CacheMode

要设置的缓存模式。

传入undefined或null时为CacheMode.Default。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State mode: CacheMode = CacheMode.None;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .cacheMode(this.mode)
  12. }
  13. }
  14. }

copyOptions11+

PhonePC/2in1TabletTVWearable

copyOptions(value: CopyOptions)

设置剪贴板复制范围选项。该属性没有显式调用时,默认支持复制后在当前设备内所有应用内粘贴。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
value CopyOptions

要设置的剪贴板复制范围选项。

传入undefined或null时为CopyOptions.None。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .copyOptions(CopyOptions.None)
  11. }
  12. }
  13. }

textZoomRatio9+

PhonePC/2in1TabletTVWearable

textZoomRatio(textZoomRatio: number)

设置页面的文本缩放百分比。当属性没有显式调用时,默认缩放百分比为100%。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
textZoomRatio number

要设置的页面的文本缩放百分比。

取值为整数,范围为(0, 2147483647]。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State ratio: number = 150;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .textZoomRatio(this.ratio)
  12. }
  13. }
  14. }

initialScale9+

PhonePC/2in1TabletTVWearable

initialScale(percent: number)

设置整体页面的缩放百分比。该属性没有显式调用时,默认缩放百分比为100。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
percent number

要设置的整体页面的缩放百分比。

取值范围:(0, 1000]。

传入undefined或null时属性设置不生效。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State percent: number = 100;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .initialScale(this.percent)
  12. }
  13. }
  14. }

blockNetwork9+

PhonePC/2in1TabletTVWearable

blockNetwork(block: boolean)

设置Web组件是否阻止从网络加载资源。当属性没有显式调用时,默认允许从网络加载资源。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
block boolean

设置Web组件是否允许从网络加载资源。

true表示不允许从网络加载资源,false表示允许从网络加载资源。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State block: boolean = true;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .blockNetwork(this.block)
  12. }
  13. }
  14. }

defaultFixedFontSize9+

PhonePC/2in1TabletTVWearable

defaultFixedFontSize(size: number)

设置网页的默认等宽字体大小。对于html前端使用monospace字体且未指定font-size样式的元素,将按此值渲染字体大小。

当属性没有显式调用时,默认等宽字体大小为13。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
size number

设置网页的默认等宽字体大小,单位px。

输入值的范围为[-2^31, 2^31-1],实际渲染时超过72px的值按照72px进行渲染,低于1px的值按照1px进行渲染。

传入null或undefined时为13。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State fontSize: number = 16;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .defaultFixedFontSize(this.fontSize)
  12. }
  13. }
  14. }

defaultFontSize9+

PhonePC/2in1TabletTVWearable

defaultFontSize(size: number)

设置网页的默认字体大小。对于html前端使用非monospace字体且未指定font-size样式的元素,将按此值渲染字体大小。

当属性没有显式调用时,网页的默认字体大小为16。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
size number

设置网页的默认字体大小,单位px。

输入值的范围为[-2^31, 2^31-1],实际渲染时超过72px的值按照72px进行渲染,低于1px的值按照1px进行渲染。

传入null或undefined时为16。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State fontSize: number = 13;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .defaultFontSize(this.fontSize)
  12. }
  13. }
  14. }

minFontSize9+

PhonePC/2in1TabletTVWearable

minFontSize(size: number)

设置网页字体大小最小值。对于html前端元素,若元素字体大小低于该接口设置值,将采用接口设置值渲染字体大小。

当属性没有显式调用时,默认网页字体大小最小值为8。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
size number

设置网页字体大小最小值,单位px。

输入值的范围为[-2^31, 2^31-1],实际渲染时超过72px的值按照72px进行渲染,低于1px的值按照1px进行渲染。

传入null或undefined时为8。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State fontSize: number = 13;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .minFontSize(this.fontSize)
  12. }
  13. }
  14. }

minLogicalFontSize9+

PhonePC/2in1TabletTVWearable

minLogicalFontSize(size: number)

设置网页逻辑字体大小最小值。

对于html前端未指定font-size样式的元素:

  1. 若元素字体大小低于该接口设置值,将采用接口设置值渲染字体大小。
  2. 若minLogicalFontSize和minFontSize同时设置时,对于未指定font-size样式元素,将采用两者中的较大值。

当属性没有显式调用时,默认网页逻辑字体大小最小值为8。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
size number

设置网页逻辑字体大小最小值,单位px。

输入值的范围为[-2^31, 2^31-1],实际渲染时超过72px的值按照72px进行渲染,低于1px的值按照1px进行渲染。

传入null或undefined时为8。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State fontSize: number = 13;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .minLogicalFontSize(this.fontSize)
  12. }
  13. }
  14. }

webFixedFont9+

PhonePC/2in1TabletTVWearable

webFixedFont(family: string)

设置网页的fixed font字体库,用于渲染html前端使用monospace字体的元素。

当属性没有显式调用时,默认网页的fixed font字体库为monospace。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
family string

设置网页的fixed font字体库。

传入null或undefined时为monospace。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State family: string = "monospace";
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .webFixedFont(this.family)
  12. }
  13. }
  14. }

webSansSerifFont9+

PhonePC/2in1TabletTVWearable

webSansSerifFont(family: string)

设置网页的sans-serif font字体库,用于渲染html前端使用sans-serif字体的元素。

当属性没有显式调用时,默认网页的sans-serif font字体库为sans-serif。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
family string

设置网页的sans-serif font字体库。

传入null或undefined时为sans-serif。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State family: string = "sans-serif";
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .webSansSerifFont(this.family)
  12. }
  13. }
  14. }

webSerifFont9+

PhonePC/2in1TabletTVWearable

webSerifFont(family: string)

设置网页的serif font字体库,用于渲染html前端使用serif字体的元素。

当属性没有显式调用时,默认网页的serif font字体库为serif。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
family string

设置网页的serif font字体库。

传入null或undefined时为serif。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State family: string = "serif";
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .webSerifFont(this.family)
  12. }
  13. }
  14. }

webStandardFont9+

PhonePC/2in1TabletTVWearable

webStandardFont(family: string)

设置网页的standard font字体库,用于渲染html前端未指定字体样式的元素。

当属性没有显式调用时,默认网页的standard font字体库为sans-serif。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
family string

设置网页的standard font字体库。

传入null或undefined时为sans-serif。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State family: string = "sans-serif";
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .webStandardFont(this.family)
  12. }
  13. }
  14. }

webFantasyFont9+

PhonePC/2in1TabletTVWearable

webFantasyFont(family: string)

设置网页的fantasy font字体库,用于渲染html前端使用fantasy字体的元素。

当属性没有显式调用时,默认网页的fantasy font字体库为fantasy。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
family string

设置网页的fantasy font字体库。

传入null或undefined时为fantasy。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State family: string = "fantasy";
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .webFantasyFont(this.family)
  12. }
  13. }
  14. }

webCursiveFont9+

PhonePC/2in1TabletTVWearable

webCursiveFont(family: string)

设置网页的cursive font字体库,用于渲染html前端使用cursive字体的元素。

当属性没有显式调用时,默认网页的cursive font字体库为cursive。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
family string

设置网页的cursive font字体库。

传入null或undefined时为cursive。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State family: string = "cursive";
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .webCursiveFont(this.family)
  12. }
  13. }
  14. }

darkMode9+

PhonePC/2in1TabletTVWearable

darkMode(mode: WebDarkMode)

设置Web深色模式。当属性没有显式调用时,默认Web深色模式关闭。

当深色模式开启时,Web将启用媒体查询prefers-color-scheme中网页所定义的深色样式,若网页未定义深色样式,则保持原状。如需开启强制深色模式,建议配合forceDarkAccess使用。深色模式具体用法可参考Web深色模式适配

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
mode WebDarkMode

设置Web的深色模式为关闭、开启或跟随系统。

传入null或undefined时为WebDarkMode.Off。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State mode: WebDarkMode = WebDarkMode.On;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .darkMode(this.mode)
  12. }
  13. }
  14. }

forceDarkAccess9+

PhonePC/2in1TabletTVWearable

forceDarkAccess(access: boolean)

设置网页是否开启强制深色模式。该属性仅在darkMode开启深色模式时生效。当属性没有显式调用时,默认网页不开启强制深色模式。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
access boolean

设置网页是否开启强制深色模式。

true表示设置网页开启强制深色模式,false表示设置网页不开启强制深色模式。

传入null或undefined时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State mode: WebDarkMode = WebDarkMode.On;
  8. @State access: boolean = true;
  9. build() {
  10. Column() {
  11. Web({ src: 'www.example.com', controller: this.controller })
  12. .darkMode(this.mode)
  13. .forceDarkAccess(this.access)
  14. }
  15. }
  16. }

pinchSmooth9+

PhonePC/2in1TabletTVWearable

pinchSmooth(isEnabled: boolean)

设置网页是否开启捏合流畅模式。该属性没有显式调用时,默认不开启捏合流畅模式。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
isEnabled boolean

网页是否开启捏合流畅模式。

true表示设置网页开启捏合流畅模式,false表示设置网页不开启捏合流畅模式。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .pinchSmooth(true)
  11. }
  12. }
  13. }

allowWindowOpenMethod10+

PhonePC/2in1TabletTVWearable

allowWindowOpenMethod(flag: boolean)

设置网页是否可以通过JavaScript自动打开新窗口。

说明
  • 该属性仅在javaScriptAccess开启时生效。
  • 该属性在multiWindowAccess开启时打开新窗口,关闭时打开本地窗口。
  • 该属性的默认值与系统属性persist.web.allowWindowOpenMethod.enabled保持一致,如果未设置系统属性则默认值为false。
  • 通过hdc shell param get persist.web.allowWindowOpenMethod.enabled 检查是否开启系统属性persist.web.allowWindowOpenMethod.enabled。若属性值为1代表开启系统属性;若属性值为0或不存在,代表未开启系统属性,可通过命令hdc shell param set persist.web.allowWindowOpenMethod.enabled 1 开启系统属性。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
flag boolean

true表示网页可以通过JavaScript自动打开新窗口,该属性为false时,用户行为仍可通过JavaScript自动打开新窗口,但非用户行为不能通过JavaScript自动打开新窗口。

此处的用户行为是指,在用户对Web组件进行点击等操作后,同时在5秒内请求打开新窗口(window.open)的行为。

默认值与系统属性关联,当系统属性persist.web.allowWindowOpenMethod.enabled为true时,默认值为true,如果未设置系统属性则默认值为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. // 在同一界面有两个Web组件。在WebComponent新开窗口时,会跳转到NewWebViewComp。
  4. @CustomDialog
  5. struct NewWebViewComp {
  6. controller?: CustomDialogController;
  7. webviewController1: webview.WebviewController = new webview.WebviewController();
  8. build() {
  9. Column() {
  10. Web({ src: "", controller: this.webviewController1 })
  11. .javaScriptAccess(true)
  12. .multiWindowAccess(false)
  13. .onWindowExit(() => {
  14. console.info("NewWebViewComp onWindowExit");
  15. if (this.controller) {
  16. this.controller.close();
  17. }
  18. })
  19. .onActivateContent(() => {
  20. // 该Web需要展示到前台,建议应用在这里进行tab或window切换的动作
  21. console.info("NewWebViewComp onActivateContent")
  22. })
  23. }
  24. }
  25. }
  26. @Entry
  27. @Component
  28. struct WebComponent {
  29. controller: webview.WebviewController = new webview.WebviewController();
  30. dialogController: CustomDialogController | null = null;
  31. build() {
  32. Column() {
  33. Web({ src: $rawfile("index.html"), controller: this.controller })
  34. .javaScriptAccess(true)
  35. // 需要使能multiWindowAccess
  36. .multiWindowAccess(true)
  37. .allowWindowOpenMethod(true)
  38. .onWindowNew((event) => {
  39. if (this.dialogController) {
  40. this.dialogController.close()
  41. }
  42. let popController: webview.WebviewController = new webview.WebviewController();
  43. // 将新窗口对应WebviewController返回给Web内核。
  44. // 若不调用event.handler.setWebController接口,会造成渲染进程阻塞。
  45. // 如果没有创建新窗口,调用event.handler.setWebController接口时设置成null,通知Web没有创建新窗口。
  46. event.handler.setWebController(popController);
  47. this.dialogController = new CustomDialogController({
  48. builder: NewWebViewComp({ webviewController1: popController }),
  49. // isModal设置为false,防止新窗口被销毁而无法触发onActivateContent回调
  50. isModal: false
  51. })
  52. this.dialogController.open();
  53. })
  54. }
  55. }
  56. }

HTML示例:

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <body>
  5. <div>
  6. <button type="button" onclick="delayOpenwindow(5000)">delayOpenwindow_5s</button>
  7. </div>
  8. <script>
  9. function openwindowAll(){
  10. open("https://www.example.com","_blank","height=400,width=600,top=100,left=100,scrollbars=no")
  11. }
  12. function delayOpenwindow(t){
  13. setTimeout(openwindowAll, t);
  14. }
  15. </script>
  16. </body>
  17. </html>

mediaOptions10+

PhonePC/2in1TabletTVWearable

mediaOptions(options: WebMediaOptions)

设置Web媒体播放的策略,其中包括:Web中的音频在重新获焦后能够自动续播的有效期、应用内多个Web实例的音频是否独占。当该属性未显式设置时,默认Web中的音频重新获焦后无法自动续播、应用内多个Web实例的音频是独占的。

说明
  • 同一Web实例中的多个音频均视为同一音频。
  • 该媒体播放策略将同时管控有声视频。
  • 建议为所有Web组件设置相同的audioExclusive值。
  • 音视频互相打断在应用内和应用间生效,续播只在应用间生效。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
options WebMediaOptions

设置Web的媒体策略。

属性参数更新后需重新播放音频方可生效。

传入undefined或null时为{resumeInterval: 0, audioExclusive: true}

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State options: WebMediaOptions = {resumeInterval: 10, audioExclusive: true};
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .mediaOptions(this.options)
  12. }
  13. }
  14. }

javaScriptOnDocumentStart11+

PhonePC/2in1TabletTVWearable

javaScriptOnDocumentStart(scripts: Array<ScriptItem>)

将JavaScript脚本注入到Web组件中,当指定页面或者文档开始加载时,该脚本将在其来源与scriptRules匹配的任何页面中执行。当属性没有显式调用时,默认不将JavaScript脚本注入到Web组件中。

说明
  • 网页文档根元素(HTML Element)创建后、但尚未加载任何其他内容之前注入脚本。

  • 该脚本按照字典序执行,非数组本身顺序,若需数组本身顺序,建议使用runJavaScriptOnDocumentStart接口。

  • 内容相同的脚本多次注入时将被静默去重,不展示,不提醒,使用首次注入时的scriptRules。

  • 本接口不支持UrlRegexRule

  • 建议使用runJavaScriptOnDocumentStart代替。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
scripts Array<ScriptItem>

需要注入的ScriptItem数组。

传入undefined或null时不将JavaScript脚本注入到Web组件中。

ets示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct Index {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. private localStorage: string =
  8. "if (typeof(Storage) !== 'undefined') {" +
  9. " localStorage.setItem('color', 'Red');" +
  10. "}";
  11. @State scripts: Array<ScriptItem> = [
  12. { script: this.localStorage, scriptRules: ["*"] }
  13. ];
  14. build() {
  15. Column({ space: 20 }) {
  16. Web({ src: $rawfile('index.html'), controller: this.controller })
  17. .javaScriptAccess(true)
  18. .domStorageAccess(true)
  19. .backgroundColor(Color.Grey)
  20. .javaScriptOnDocumentStart(this.scripts)
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }
  25. }

HTML示例:

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. </head>
  7. <body style="font-size: 30px;" onload='bodyOnLoadLocalStorage()'>
  8. Hello world!
  9. <div id="result"></div>
  10. </body>
  11. <script type="text/javascript">
  12. function bodyOnLoadLocalStorage() {
  13. if (typeof(Storage) !== 'undefined') {
  14. document.getElementById('result').innerHTML = localStorage.getItem('color');
  15. } else {
  16. document.getElementById('result').innerHTML = 'Your browser does not support localStorage.';
  17. }
  18. }
  19. </script>
  20. </html>

javaScriptOnDocumentEnd11+

PhonePC/2in1TabletTVWearable

javaScriptOnDocumentEnd(scripts: Array<ScriptItem>)

将JavaScript脚本注入到Web组件中,当指定页面或者文档加载完成时,该脚本将在其来源与scriptRules匹配的任何页面中执行。当属性没有显式调用时,默认不将JavaScript脚本注入到Web组件中。

说明
  • 该脚本将在页面的任何JavaScript代码之后运行,并且DOM树此时已经加载、渲染完毕。

  • 该脚本按照字典序执行,非数组本身顺序。

  • 内容相同的脚本多次注入时将被静默去重,不展示,不提醒,使用首次注入时的scriptRules。

  • 本接口不支持UrlRegexRule

  • 建议使用runJavaScriptOnDocumentEnd代替。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
scripts Array<ScriptItem>

需要注入的ScriptItem数组。

传入undefined或null时不将JavaScript脚本注入到Web组件中。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct Index {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. private jsStr: string =
  8. "window.document.getElementById(\"result\").innerHTML = 'this is msg from javaScriptOnDocumentEnd'";
  9. @State scripts: Array<ScriptItem> = [
  10. { script: this.jsStr, scriptRules: ["*"] }
  11. ];
  12. build() {
  13. Column({ space: 20 }) {
  14. Web({ src: $rawfile('index.html'), controller: this.controller })
  15. .javaScriptAccess(true)
  16. .domStorageAccess(true)
  17. .backgroundColor(Color.Grey)
  18. .javaScriptOnDocumentEnd(this.scripts)
  19. .width('100%')
  20. .height('100%')
  21. }
  22. }
  23. }
收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. </head>
  7. <body style="font-size: 30px;">
  8. Hello world!
  9. <div id="result">test msg</div>
  10. </body>
  11. </html>

runJavaScriptOnDocumentStart15+

PhonePC/2in1TabletTVWearable

runJavaScriptOnDocumentStart(scripts: Array<ScriptItem>)

将JavaScript脚本注入到Web组件中,当指定页面或者文档开始加载时,该脚本将在其来源与scriptRules匹配的任何页面中执行。当属性没有显式调用时,默认不将JavaScript脚本注入到Web组件中。

说明
  • 网页文档根元素(HTML Element)创建后、但尚未加载任何其他内容之前注入脚本。

  • 该脚本按照数组本身顺序执行。

  • 内容相同的脚本多次注入时将被静默去重,不展示,不提醒,使用首次注入时的scriptRules。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
scripts Array<ScriptItem>

需要注入的ScriptItem数组。

传入undefined或null时不将JavaScript脚本注入到Web组件中。

ets示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct Index {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. private localStorage: string =
  8. "if (typeof(Storage) !== 'undefined') {" +
  9. " localStorage.setItem('color', 'Red');" +
  10. "}";
  11. private localStorage2: string =
  12. "console.info('runJavaScriptOnDocumentStart urlRegexRules Matching succeeded.')";
  13. @State scripts: Array<ScriptItem> = [
  14. { script: this.localStorage, scriptRules: ["*"] },
  15. { script: this.localStorage2, scriptRules: [], urlRegexRules: [{secondLevelDomain: "", rule: ".*index.html"}] }
  16. ];
  17. build() {
  18. Column({ space: 20 }) {
  19. Web({ src: $rawfile('index.html'), controller: this.controller })
  20. .javaScriptAccess(true)
  21. .domStorageAccess(true)
  22. .backgroundColor(Color.Grey)
  23. .runJavaScriptOnDocumentStart(this.scripts)
  24. .width('100%')
  25. .height('100%')
  26. }
  27. }
  28. }

HTML示例:

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. </head>
  7. <body style="font-size: 30px;" onload='bodyOnLoadLocalStorage()'>
  8. Hello world!
  9. <div id="result"></div>
  10. </body>
  11. <script type="text/javascript">
  12. function bodyOnLoadLocalStorage() {
  13. if (typeof(Storage) !== 'undefined') {
  14. document.getElementById('result').innerHTML = localStorage.getItem('color');
  15. } else {
  16. document.getElementById('result').innerHTML = 'Your browser does not support localStorage.';
  17. }
  18. }
  19. </script>
  20. </html>

runJavaScriptOnDocumentEnd15+

PhonePC/2in1TabletTVWearable

runJavaScriptOnDocumentEnd(scripts: Array<ScriptItem>)

将JavaScript脚本注入到Web组件中,当指定页面或者文档加载完成时,该脚本将在其来源与scriptRules匹配的任何页面中执行。当属性没有显式调用时,默认不将JavaScript脚本注入到Web组件中。

说明
  • 该脚本将在页面的任何JavaScript代码之后运行,并且DOM树此时已经加载、渲染完毕。

  • 该脚本按照数组本身顺序执行。

  • 内容相同的脚本多次注入时将被静默去重,不展示,不提醒,使用首次注入时的scriptRules。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
scripts Array<ScriptItem>

需要注入的ScriptItem数组。

传入undefined或null时不将JavaScript脚本注入到Web组件中。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct Index {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. private jsStr: string =
  8. "window.document.getElementById(\"result\").innerHTML = 'this is msg from runJavaScriptOnDocumentEnd'";
  9. private jsStr2: string = "console.info('runJavaScriptOnDocumentEnd urlRegexRules Matching succeeded.')";
  10. @State scripts: Array<ScriptItem> = [
  11. { script: this.jsStr, scriptRules: ["*"] },
  12. { script: this.jsStr2, scriptRules: [], urlRegexRules: [{secondLevelDomain: "", rule: ".*index.html"}] }
  13. ];
  14. build() {
  15. Column({ space: 20 }) {
  16. Web({ src: $rawfile('index.html'), controller: this.controller })
  17. .javaScriptAccess(true)
  18. .domStorageAccess(true)
  19. .backgroundColor(Color.Grey)
  20. .runJavaScriptOnDocumentEnd(this.scripts)
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }
  25. }
收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. </head>
  7. <body style="font-size: 30px;">
  8. Hello world!
  9. <div id="result">test msg</div>
  10. </body>
  11. </html>

runJavaScriptOnHeadEnd15+

PhonePC/2in1TabletTVWearable

runJavaScriptOnHeadEnd(scripts: Array<ScriptItem>)

将JavaScript脚本注入到Web组件中,当页面DOM树head标签解析完成时,该脚本将在其来源与scriptRules匹配的任何页面中执行。当属性没有显式调用时,默认不将JavaScript脚本注入到Web组件中。

说明
  • 该脚本按照数组本身顺序执行。

  • 内容相同的脚本多次注入时将被静默去重,不展示,不提醒,使用首次注入时的scriptRules。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
scripts Array<ScriptItem>

需要注入的ScriptItem数组。

传入undefined或null时不将JavaScript脚本注入到Web组件中。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct Index {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. private jsStr: string =
  8. "window.document.getElementById(\"result\").innerHTML = 'this is msg from runJavaScriptOnHeadEnd'";
  9. private jsStr2: string = "console.info('runJavaScriptOnHeadEnd urlRegexRules Matching succeeded.')";
  10. @State scripts: Array<ScriptItem> = [
  11. { script: this.jsStr, scriptRules: ["*"] },
  12. { script: this.jsStr2, scriptRules: [], urlRegexRules: [{secondLevelDomain: "", rule: ".*index.html"}] }
  13. ];
  14. build() {
  15. Column({ space: 20 }) {
  16. Web({ src: $rawfile('index.html'), controller: this.controller })
  17. .javaScriptAccess(true)
  18. .domStorageAccess(true)
  19. .backgroundColor(Color.Grey)
  20. .runJavaScriptOnHeadEnd(this.scripts)
  21. .width('100%')
  22. .height('100%')
  23. }
  24. }
  25. }
收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. </head>
  7. <body style="font-size: 30px;">
  8. Hello world!
  9. <div id="result">test msg</div>
  10. </body>
  11. </html>

layoutMode11+

PhonePC/2in1TabletTVWearable

layoutMode(mode: WebLayoutMode)

设置Web布局模式。当属性没有显式调用时,默认Web布局跟随系统模式。常见问题请参考Web组件大小自适应页面内容布局

说明

目前只支持两种Web布局模式,分别为Web布局跟随系统(WebLayoutMode.NONE)和Web组件高度基于前端页面高度的自适应网页布局(WebLayoutMode.FIT_CONTENT)。

Web组件高度基于前端页面自适应布局有如下限制:

  • 如果Web组件宽或长度超过7680px,请在Web组件创建的时候指定RenderMode.SYNC_RENDER模式,否则会整个白屏。
  • Web组件创建后不支持动态切换layoutMode模式。
  • Web组件宽高规格:指定RenderMode.ASYNC_RENDER模式时,分别不超过7680px。
  • 频繁更改页面宽高会触发Web组件重新布局,影响体验。
  • 不支持瀑布流网页(下拉到底部加载更多)。
  • 不支持宽度自适应,仅支持高度自适应。
  • 由于高度自适应网页高度,您无法通过修改组件高度属性来修改组件高度。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
mode WebLayoutMode

设置Web布局模式,跟随系统或自适应布局。

传入null或undefined时为WebLayoutMode.NONE

示例:

1、指明layoutMode为WebLayoutMode.FIT_CONTENT模式,为避免默认渲染模式下(RenderMode.ASYNC_RENDER)视口高度超过7680px导致页面渲染出错,需要显式指明渲染模式(RenderMode.SYNC_RENDER)。

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. mode: WebLayoutMode = WebLayoutMode.FIT_CONTENT;
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller, renderMode: RenderMode.SYNC_RENDER })
  11. .layoutMode(this.mode)
  12. }
  13. }
  14. }

2、指明layoutMode为WebLayoutMode.FIT_CONTENT模式,为避免嵌套滚动场景下,Web滚动到边缘时会优先触发过滚动的过界回弹效果影响用户体验,建议指定overScrollMode为OverScrollMode.NEVER。

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. layoutMode: WebLayoutMode = WebLayoutMode.FIT_CONTENT;
  8. @State overScrollMode: OverScrollMode = OverScrollMode.NEVER;
  9. build() {
  10. Column() {
  11. Web({ src: 'www.example.com', controller: this.controller, renderMode: RenderMode.SYNC_RENDER })
  12. .layoutMode(this.layoutMode)
  13. .overScrollMode(this.overScrollMode)
  14. }
  15. }
  16. }

nestedScroll11+

PhonePC/2in1TabletTVWearable

nestedScroll(value: NestedScrollOptions | NestedScrollOptionsExt)

调用以设置嵌套滚动选项。

说明
  • 可以设置上下左右四个方向,或者设置向前、向后两个方向的嵌套滚动模式,实现与父组件的滚动联动。
  • 支持嵌套滚动的容器:GridListScrollSwiperTabsWaterFlowRefreshbindSheet
  • 支持嵌套滚动的输入事件:使用手势、鼠标、触控板。
  • 嵌套滚动场景下,由于Web滚动到边缘时会优先触发过滚动的过界回弹效果,建议设置overScrollMode为OverScrollMode.NEVER,避免影响此场景的用户体验。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
value NestedScrollOptions | NestedScrollOptionsExt14+

可滚动组件滚动时的嵌套滚动选项。

value为NestedScrollOptions(向前、向后两个方向)类型时,scrollForward、scrollBackward默认滚动选项为NestedScrollMode.SELF_FIRST

value为NestedScrollOptionsExt(上下左右四个方向)类型时,scrollUp、scrollDown、scrollLeft、scrollRight默认滚动选项为NestedScrollMode.SELF_FIRST。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .nestedScroll({
  11. scrollForward: NestedScrollMode.SELF_FIRST,
  12. scrollBackward: NestedScrollMode.SELF_FIRST,
  13. })
  14. }
  15. }
  16. }
收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController()
  7. build() {
  8. Scroll(){
  9. Column() {
  10. Text("嵌套Web")
  11. .height("25%")
  12. .width("100%")
  13. .fontSize(30)
  14. .backgroundColor(Color.Yellow)
  15. Web({ src: $rawfile('index.html'),
  16. controller: this.controller })
  17. .nestedScroll({
  18. scrollUp: NestedScrollMode.SELF_FIRST,
  19. scrollDown: NestedScrollMode.PARENT_FIRST,
  20. scrollLeft: NestedScrollMode.SELF_FIRST,
  21. scrollRight: NestedScrollMode.SELF_FIRST,
  22. })
  23. }
  24. }
  25. }
  26. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0">
  6. <style>
  7. .blue {
  8. background-color: lightblue;
  9. }
  10. .green {
  11. background-color: lightgreen;
  12. }
  13. .blue, .green {
  14. font-size:16px;
  15. height:200px;
  16. text-align: center; /* 水平居中 */
  17. line-height: 200px; /* 垂直居中(值等于容器高度) */
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <div class="blue" >webArea</div>
  23. <div class="green">webArea</div>
  24. <div class="blue">webArea</div>
  25. <div class="green">webArea</div>
  26. <div class="blue">webArea</div>
  27. <div class="green">webArea</div>
  28. <div class="blue">webArea</div>
  29. </body>
  30. </html>

enableScrollDirectionalLockBeta

PhonePC/2in1TabletTVWearable

enableScrollDirectionalLock(value: boolean, type: ScrollDirectionalLockType)

设置Web组件滑动方向锁定。不调用该方法设置时,默认在嵌套滚动场景下支持滑动方向锁定。

系统能力: SystemCapability.Web.Webview.Core

起始版本: 26.0.0

模型约束: 此接口仅可在Stage模型下使用。

参数:

展开
参数名 类型 必填 说明
value boolean 是否支持滑动方向锁定。true 表示滑动方向锁定,滚动视图会根据用户初始滑动的方向来锁定滚动轴,false 表示不锁定。
type ScrollDirectionalLockType 设置Web组件在哪些场景下希望滑动方向锁定。ALL表示所有场景都支持滑动锁定,NESTED_SCROLL表示在嵌套滚动场景下支持滑动锁定。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .width('100%')
  11. .height('100%')
  12. // 在所有场景下支持滑动方向的锁定
  13. .enableScrollDirectionalLock(true, ScrollDirectionalLockType.ALL)
  14. }
  15. }
  16. }

bypassVsyncCondition20+

PhonePC/2in1TabletTVWearable

bypassVsyncCondition(condition: WebBypassVsyncCondition)

当开发者调用scrollBy接口进行页面滚动时,可以通过bypassVsyncCondition接口设置渲染流程跳过vsync(垂直同步)调度,直接触发绘制。该属性没有显式调用时,默认不跳过vsync调度。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
condition WebBypassVsyncCondition

触发渲染流程跳过vsync调度的条件。

传入undefined或null时为NONE。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. condition: WebBypassVsyncCondition = WebBypassVsyncCondition.SCROLLBY_FROM_ZERO_OFFSET;
  8. build() {
  9. Column() {
  10. Button('scrollBy')
  11. .onClick(() => {
  12. this.controller.scrollBy(0, 5);
  13. })
  14. Web({ src: 'www.example.com', controller: this.controller })
  15. .bypassVsyncCondition(this.condition)
  16. }
  17. }
  18. }

enableNativeEmbedMode11+

PhonePC/2in1TabletTVWearable

enableNativeEmbedMode(enabled: boolean)

设置是否开启同层渲染功能。当该方法没有显式调用时,默认不开启同层渲染功能。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
enabled boolean

是否开启同层渲染功能。

true表示开启同层渲染功能,false表示不开启同层渲染功能。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .enableNativeEmbedMode(true)
  11. }
  12. }
  13. }

forceDisplayScrollBar14+

PhonePC/2in1TabletTVWearable

forceDisplayScrollBar(enabled: boolean)

设置滚动条是否常驻。在常驻状态下,当页面大小超过一页时,滚动条出现且不消失。该属性没有显式调用时,默认设置滚动条不常驻。

全量展开模式下不支持滚动条常驻,即layoutMode为WebLayoutMode.FIT_CONTENT模式时,参数enabled为false。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
enabled boolean

滚动条是否常驻。

true表示滚动条常驻,false表示滚动条不常驻。

传入undefined或null时属性设置不生效。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile('index.html'), controller: this.controller })
  10. .forceDisplayScrollBar(true)
  11. }
  12. }
  13. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Demo</title>
  7. <style>
  8. body {
  9. width:2560px;
  10. height:2560px;
  11. padding-right:170px;
  12. padding-left:170px;
  13. border:5px solid blueviolet;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. Scroll Test
  19. </body>
  20. </html>

registerNativeEmbedRule12+

PhonePC/2in1TabletTVWearable

registerNativeEmbedRule(tag: string, type: string)

注册使用同层渲染的HTML标签名和类型。标签名仅支持使用<object>和<embed>。标签类型只能使用ASCII可显示字符。

若指定类型与W3C定义的<object>或<embed>标准类型重合,ArkWeb内核将其识别为非同层标签。

本接口同样受enableNativeEmbedMode接口控制,在未使能同层渲染时本接口无效。在不使用本接口的情况下,ArkWeb内核默认将"native/"前缀类型的<embed>标签识别为同层标签。

具体使用详情请参考同层渲染指南。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
tag string 标签名。
type string 标签类型,内核使用前缀匹配此参数。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. import { NodeController, BuilderNode, NodeRenderType, FrameNode, UIContext } from '@kit.ArkUI';
  4. declare class Params {
  5. text: string;
  6. width: number;
  7. height: number;
  8. }
  9. declare class NodeControllerParams {
  10. surfaceId: string;
  11. renderType: NodeRenderType;
  12. width: number;
  13. height: number;
  14. }
  15. class MyNodeController extends NodeController {
  16. private rootNode: BuilderNode<[Params]> | undefined | null;
  17. private surfaceId_: string = "";
  18. private renderType_: NodeRenderType = NodeRenderType.RENDER_TYPE_DISPLAY;
  19. private width_: number = 0;
  20. private height_: number = 0;
  21. setRenderOption(params: NodeControllerParams) {
  22. this.surfaceId_ = params.surfaceId;
  23. this.renderType_ = params.renderType;
  24. this.width_ = params.width;
  25. this.height_ = params.height;
  26. }
  27. makeNode(uiContext: UIContext): FrameNode | null {
  28. this.rootNode = new BuilderNode(uiContext, { surfaceId: this.surfaceId_, type: this.renderType_ });
  29. this.rootNode.build(wrapBuilder(ButtonBuilder), { text: "myButton", width: this.width_, height: this.height_ });
  30. return this.rootNode.getFrameNode();
  31. }
  32. postInputEvent(event: TouchEvent | MouseEvent | undefined): boolean {
  33. return this.rootNode?.postInputEvent(event) as boolean;
  34. }
  35. }
  36. @Component
  37. struct ButtonComponent {
  38. @Prop params: Params;
  39. @State bkColor: Color = Color.Red;
  40. build() {
  41. Column() {
  42. Button(this.params.text)
  43. .height(50)
  44. .width(200)
  45. .border({ width: 2, color: Color.Red })
  46. .backgroundColor(this.bkColor)
  47. }
  48. .width(this.params.width)
  49. .height(this.params.height)
  50. }
  51. }
  52. @Builder
  53. function ButtonBuilder(params: Params) {
  54. ButtonComponent({ params: params })
  55. .backgroundColor(Color.Green)
  56. }
  57. @Entry
  58. @Component
  59. struct WebComponent {
  60. controller: webview.WebviewController = new webview.WebviewController();
  61. private nodeController: MyNodeController = new MyNodeController();
  62. uiContext: UIContext = this.getUIContext();
  63. build() {
  64. Column() {
  65. Stack() {
  66. NodeContainer(this.nodeController)
  67. Web({ src: $rawfile('index.html'), controller: this.controller })
  68. // 配置同层渲染开关开启。
  69. .enableNativeEmbedMode(true)
  70. // 注册同层标签为<object>,类型为"native"前缀。
  71. .registerNativeEmbedRule("object", "native")
  72. // 获取<object>标签的生命周期变化数据。
  73. .onNativeEmbedLifecycleChange((object) => {
  74. if (object.status == NativeEmbedStatus.CREATE) {
  75. this.nodeController.setRenderOption({
  76. surfaceId: object.surfaceId as string,
  77. renderType: NodeRenderType.RENDER_TYPE_TEXTURE,
  78. width: this.uiContext!.px2vp(object.info?.width),
  79. height: this.uiContext!.px2vp(object.info?.height)
  80. });
  81. this.nodeController.rebuild();
  82. }
  83. })
  84. }
  85. }
  86. }
  87. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>同层渲染测试</title>
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. </head>
  8. <body>
  9. <div>
  10. <div id="bodyId">
  11. <object id="nativeButton" type ="native/button" width="300" height="300" style="background-color:red">
  12. </object>
  13. </div>
  14. </div>
  15. </body>
  16. </html>

defaultTextEncodingFormat12+

PhonePC/2in1TabletTVWearable

defaultTextEncodingFormat(textEncodingFormat: string)

设置网页的默认字符编码。当属性没有显式调用时,网页的默认字符编码为"UTF-8"。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
textEncodingFormat string

默认字符编码。

传入null或undefined时为"UTF-8"。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile('index.html'), controller: this.controller })
  10. // 设置高
  11. .height(500)
  12. .defaultTextEncodingFormat("UTF-8")
  13. .javaScriptAccess(true)
  14. }
  15. }
  16. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta name="viewport" content="width=device-width" />
  6. <title>My test html5 page</title>
  7. </head>
  8. <body>
  9. <p>hello world, 你好世界!</p>
  10. </body>
  11. </html>

metaViewport12+

PhonePC/2in1TabletTVWearable

metaViewport(enabled: boolean)

设置meta标签的viewport属性是否可用。当属性没有显式调用时,默认支持meta标签的viewport属性。

说明
  • 当前通过User-Agent中是否含有"Mobile"字段来判断是否开启前端HTML页面中meta标签的viewport属性。当User-Agent中不含有"Mobile"字段时,meta标签中viewport属性默认关闭,此时可通过显式设置metaViewport属性为true来覆盖关闭状态。

系统能力: SystemCapability.Web.Webview.Core

设备行为差异: 该接口在Phone、Wearable、TV设备中可正常调用,在PC/2in1设备中无效果,在Tablet设备中,设置为true或false均会解析meta标签viewport-fit属性。当viewport-fit=cover时,可通过CSS属性获取安全区域大小。

参数:

展开
参数名 类型 必填 说明
enabled boolean

是否支持meta标签的viewport属性。

true表示支持meta标签的viewport属性,将解析viewport属性,并根据viewport属性布局。

false表示不支持meta标签的viewport属性,将不解析viewport属性,进行默认布局。

传入null或undefined时为true。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile('index.html'), controller: this.controller })
  10. .metaViewport(true)
  11. }
  12. }
  13. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. </head>
  7. <body>
  8. <p>hello world, 你好世界!</p>
  9. </body>
  10. </html>

textAutosizing12+

PhonePC/2in1TabletTVWearable

textAutosizing(textAutosizing: boolean)

设置Web组件是否开启文本字体大小自动调整。当属性没有显式调用时,Web组件默认开启文本字体大小自动调整。

文本字体大小自动调整生效后,对于字号过小的文本将自动加大字号至16px~32px,避免屏幕较小(默认视口宽度 < 980px)的设备因为缺少移动端适配出现字体过小的可读性问题。

说明
  • 文本字体大小自动调整生效需要满足的前置条件:
    • 设备形态为:Phone、Tablet、Wearable、TV。
    • Web组件视口宽度 < 980px。
    • 页面文本量大,页面文本的字号*字符数 ≥ 3920。
    • 前端无metaViewport设置,或metaViewport设置中无"width"和"initial-scale"属性。

系统能力: SystemCapability.Web.Webview.Core

设备行为差异: 该接口在PC/2in1设备中无效果,在其他设备中可正常调用。

参数:

展开
参数名 类型 必填 说明
textAutosizing boolean

文本自动调整大小。

true表示文本自动调整大小,false表示文本不自动调整大小。

传入undefined或null时为true。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .textAutosizing(false)
  11. }
  12. }
  13. }

enableNativeMediaPlayer12+

PhonePC/2in1TabletTVWearable

enableNativeMediaPlayer(config: NativeMediaPlayerConfig)

开启应用接管网页媒体播放功能。当属性没有显式调用时,默认不开启接管网页媒体播放功能。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
config NativeMediaPlayerConfig

enable: 是否开启该功能。

shouldOverlay: 该功能开启后, 应用接管网页视频的播放器画面是否覆盖网页内容。

传入undefined或null时为{enable: false, shouldOverlay: false}。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .enableNativeMediaPlayer({enable: true, shouldOverlay: false})
  11. }
  12. }
  13. }

onAdsBlocked12+

PhonePC/2in1TabletTVWearable

onAdsBlocked(callback: OnAdsBlockedCallback)

一个页面发生广告过滤后,通过此回调接口通知过滤的详细信息。由于页面可能随时发生变化并不断产生网络请求,为了减少通知频次、降低对页面加载过程的影响,仅在页面加载完成时进行首次通知,此后发生的过滤将间隔1秒钟上报,无广告过滤则无通知。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
callback OnAdsBlockedCallback 广告过滤的回调。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. @State totalAdsBlockCounts: number = 0;
  7. controller: webview.WebviewController = new webview.WebviewController();
  8. build() {
  9. Column() {
  10. Web({ src: 'https://www.example.com', controller: this.controller })
  11. .onAdsBlocked((details: AdsBlockedDetails) => {
  12. if (details) {
  13. console.info(' Blocked ' + details.adsBlocked.length + ' in ' + details.url);
  14. let adList: Array<string> = Array.from(new Set(details.adsBlocked));
  15. this.totalAdsBlockCounts += adList.length;
  16. console.info('Total blocked counts :' + this.totalAdsBlockCounts);
  17. }
  18. })
  19. }
  20. }
  21. }

keyboardAvoidMode12+

PhonePC/2in1TabletTVWearable

keyboardAvoidMode(mode: WebKeyboardAvoidMode)

Web组件自定义软件键盘避让模式。

当UIContext设置的键盘避让模式为KeyboardAvoidMode.RESIZE模式时,该接口功能不生效。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
mode WebKeyboardAvoidMode

Web软键盘避让模式。

嵌套滚动场景下不推荐使用web软键盘避让,包括RESIZE_VISUAL与RESIZE_CONTENT。

默认值:WebKeyboardAvoidMode.RESIZE_CONTENT避让行为。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State avoidMode: WebKeyboardAvoidMode = WebKeyboardAvoidMode.RESIZE_VISUAL;
  8. build() {
  9. Column() {
  10. Web({ src: $rawfile("index.html"), controller: this.controller })
  11. .keyboardAvoidMode(this.avoidMode)
  12. }
  13. }
  14. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>测试网页</title>
  6. </head>
  7. <body>
  8. <input type="text" placeholder="Text">
  9. </body>
  10. </html>

editMenuOptions12+

PhonePC/2in1TabletTVWearable

editMenuOptions(editMenu: EditMenuOptions)

设置Web组件自定义文本选择菜单。

用户可以通过该属性设置自定义的文本菜单。

onCreateMenu中,可以修改、增加、删除菜单选项,如果希望不显示文本菜单,需要返回空数组。

onMenuItemClick中,可以自定义菜单选项的回调函数。该函数在菜单选项被点击后触发,并根据返回值决定是否执行系统默认的回调。返回true不执行系统回调,返回false继续执行系统回调。

onPrepareMenu20+中,当文本选择区域变化后显示菜单之前触发该回调,可在该回调中进行修改、增加、删除菜单选项,实现动态更新菜单。

本接口在与selectionMenuOptions(deprecated)同时使用时,会使selectionMenuOptions(deprecated)不生效。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
editMenu EditMenuOptions

Web自定义文本菜单选项。

菜单项数量,及菜单的content大小、icon图标尺寸,与ArkUI Menu组件保持一致。

菜单中系统自带的id枚举值(TextMenuItemId)在Web中仅支持CUT、COPY、PASTE、SELECT_ALL、TRANSLATE、SEARCH、AI_WRITER七项。

onMenuItemClick函数中textRange参数在Web中无意义,传入值为-1。

示例

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. let selectText:string = '';
  4. class TestClass {
  5. setSelectText(param: String) {
  6. selectText = param.toString();
  7. }
  8. }
  9. @Entry
  10. @Component
  11. struct WebComponent {
  12. controller: webview.WebviewController = new webview.WebviewController();
  13. @State testObj: TestClass = new TestClass();
  14. onCreateMenu(menuItems: Array<TextMenuItem>): Array<TextMenuItem> {
  15. let items = menuItems.filter((menuItem) => {
  16. // 过滤用户需要的系统按键
  17. return (
  18. menuItem.id.equals(TextMenuItemId.CUT) ||
  19. menuItem.id.equals(TextMenuItemId.COPY) ||
  20. menuItem.id.equals((TextMenuItemId.PASTE)) ||
  21. menuItem.id.equals((TextMenuItemId.TRANSLATE)) ||
  22. menuItem.id.equals((TextMenuItemId.SEARCH)) ||
  23. menuItem.id.equals((TextMenuItemId.AI_WRITER))
  24. )
  25. });
  26. let customItem1: TextMenuItem = {
  27. content: 'customItem1',
  28. id: TextMenuItemId.of('customItem1'),
  29. icon: $r('app.media.icon')
  30. };
  31. let customItem2: TextMenuItem = {
  32. content: $r('app.string.customItem2'),
  33. id: TextMenuItemId.of('customItem2'),
  34. icon: $r('app.media.icon')
  35. };
  36. items.push(customItem1);// 在选项列表后添加新选项
  37. items.unshift(customItem2);// 在选项列表前添加选项
  38. return items;
  39. }
  40. onMenuItemClick(menuItem: TextMenuItem, textRange: TextRange): boolean {
  41. if (menuItem.id.equals(TextMenuItemId.CUT)) {
  42. // 用户自定义行为
  43. console.info("拦截 id:CUT")
  44. return true; // 返回true不执行系统回调
  45. } else if (menuItem.id.equals(TextMenuItemId.COPY)) {
  46. // 用户自定义行为
  47. console.info("不拦截 id:COPY")
  48. return false; // 返回false执行系统回调
  49. } else if (menuItem.id.equals(TextMenuItemId.of('customItem1'))) {
  50. // 用户自定义行为
  51. console.info("拦截 id:customItem1")
  52. return true;// 用户自定义菜单选项返回true时点击后不关闭菜单,返回false时关闭菜单
  53. } else if (menuItem.id.equals((TextMenuItemId.of($r('app.string.customItem2'))))){
  54. // 用户自定义行为
  55. console.info("拦截 id:app.string.customItem2")
  56. return true;
  57. }
  58. return false;// 返回默认值false
  59. }
  60. onPrepareMenu = (menuItems: Array<TextMenuItem>) => {
  61. let item1: TextMenuItem = {
  62. content: 'prepare1',
  63. id: TextMenuItemId.of('prepareMenu1'),
  64. };
  65. let item2: TextMenuItem = {
  66. content: 'prepare2' + selectText,
  67. id: TextMenuItemId.of('prepareMenu2'),
  68. };
  69. menuItems.push(item1);// 在选项列表后添加新选项
  70. menuItems.unshift(item2);// 在选项列表前添加选项
  71. return menuItems;
  72. }
  73. @State EditMenuOptions: EditMenuOptions =
  74. { onCreateMenu: this.onCreateMenu, onMenuItemClick: this.onMenuItemClick, onPrepareMenu:this.onPrepareMenu }
  75. build() {
  76. Column() {
  77. Web({ src: $rawfile("index.html"), controller: this.controller })
  78. .editMenuOptions(this.EditMenuOptions)
  79. .javaScriptProxy({
  80. object: this.testObj,
  81. name: "testObjName",
  82. methodList: ["setSelectText"],
  83. controller: this.controller,
  84. })
  85. }
  86. }
  87. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>测试网页</title>
  6. </head>
  7. <body>
  8. <h1>editMenuOptions Demo</h1>
  9. <span>edit menu options</span>
  10. <script>
  11. document.addEventListener('selectionchange', () => {
  12. var selection = window.getSelection();
  13. if (selection.rangeCount > 0) {
  14. var selectedText = selection.toString();
  15. testObjName.setSelectText(selectedText);
  16. }
  17. });
  18. </script>
  19. </body>
  20. </html>

enableHapticFeedback13+

PhonePC/2in1TabletTVWearable

enableHapticFeedback(enabled: boolean)

设置Web组件长按文本选择是否开启振动。需配置"ohos.permission.VIBRATE"。该属性没有显式调用时,默认开启振动。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
enabled boolean

是否开启振动。

true表示开启振动,false表示不开启振动。

传入undefined或null时属性设置不生效。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile("index.html"), controller: this.controller })
  10. .enableHapticFeedback(true)
  11. }
  12. }
  13. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>测试网页</title>
  6. </head>
  7. <body>
  8. <h1>enableHapticFeedback Demo</h1>
  9. <span>enable haptic feedback</span>
  10. </body>
  11. </html>

bindSelectionMenu13+

PhonePC/2in1TabletTVWearable

bindSelectionMenu(elementType: WebElementType, content: CustomBuilder, responseType: WebResponseType, options?: SelectionMenuOptionsExt)

设置自定义选择菜单。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
elementType WebElementType 菜单的类型。
content CustomBuilder 菜单的内容。
responseType WebResponseType 菜单的响应类型。
options SelectionMenuOptionsExt 菜单的选项。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. import { pasteboard } from '@kit.BasicServicesKit';
  4. import { BusinessError } from '@kit.BasicServicesKit';
  5. interface PreviewBuilderParam {
  6. width: number;
  7. height: number;
  8. url:Resource | string | undefined;
  9. }
  10. interface PreviewBuilderParamForImage {
  11. previewImage: Resource | string | undefined;
  12. width: number;
  13. height: number;
  14. }
  15. @Builder function PreviewBuilderGlobalForImage($$: PreviewBuilderParamForImage) {
  16. Column() {
  17. Image($$.previewImage)
  18. .objectFit(ImageFit.Fill)
  19. .autoResize(true)
  20. }.width($$.width).height($$.height)
  21. }
  22. @Entry
  23. @Component
  24. struct SelectionMenuLongPress {
  25. controller: webview.WebviewController = new webview.WebviewController();
  26. previewController: webview.WebviewController = new webview.WebviewController();
  27. @Builder PreviewBuilder($$: PreviewBuilderParam){
  28. Column() {
  29. Stack(){
  30. Text("") // 可选择是否展示url
  31. .padding(5)
  32. .width('100%')
  33. .textAlign(TextAlign.Start)
  34. .backgroundColor(Color.White)
  35. .copyOption(CopyOptions.LocalDevice)
  36. .maxLines(1)
  37. .textOverflow({overflow:TextOverflow.Ellipsis})
  38. Progress({ value: this.progressValue, total: 100, type: ProgressType.Linear }) // 展示进度条
  39. .style({ strokeWidth: 3, enableSmoothEffect: true })
  40. .backgroundColor(Color.White)
  41. .opacity(this.progressVisible?1:0)
  42. .backgroundColor(Color.White)
  43. }.alignContent(Alignment.Bottom)
  44. Web({src:$$.url,controller: new webview.WebviewController()})
  45. .javaScriptAccess(true)
  46. .fileAccess(true)
  47. .onlineImageAccess(true)
  48. .imageAccess(true)
  49. .domStorageAccess(true)
  50. .onPageBegin(()=>{
  51. this.progressValue = 0;
  52. this.progressVisible = true;
  53. })
  54. .onProgressChange((event)=>{
  55. this.progressValue = event.newProgress;
  56. })
  57. .onPageEnd(()=>{
  58. this.progressVisible = false;
  59. })
  60. .hitTestBehavior(HitTestMode.None) // 使预览Web不响应手势
  61. }.width($$.width).height($$.height) // 设置预览宽高
  62. }
  63. private result: WebContextMenuResult | undefined = undefined;
  64. @State previewImage: Resource | string | undefined = undefined;
  65. @State previewWidth: number = 1;
  66. @State previewHeight: number = 1;
  67. @State previewWidthImage: number = 1;
  68. @State previewHeightImage: number = 1;
  69. @State linkURL:string = "";
  70. @State progressValue:number = 0;
  71. @State progressVisible:boolean = true;
  72. uiContext: UIContext = this.getUIContext();
  73. enablePaste = false;
  74. clearSelection() {
  75. try {
  76. this.controller.runJavaScript(
  77. 'clearSelection()',
  78. (error, result) => {
  79. if (error) {
  80. console.error(`run clearSelection JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
  81. return;
  82. }
  83. if (result) {
  84. console.info(`The clearSelection() return value is: ${result}`);
  85. }
  86. });
  87. } catch (error) {
  88. console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
  89. }
  90. }
  91. @Builder
  92. LinkMenuBuilder() {
  93. Menu() {
  94. MenuItem({ content: '复制链接', })
  95. .onClick(() => {
  96. const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, this.linkURL);
  97. const systemPasteboard = pasteboard.getSystemPasteboard();
  98. systemPasteboard.setData(pasteboardData);
  99. })
  100. MenuItem({content:'打开链接'})
  101. .onClick(()=>{
  102. this.controller.loadUrl(this.linkURL);
  103. })
  104. }
  105. }
  106. @Builder
  107. ImageMenuBuilder() {
  108. Menu() {
  109. MenuItem({ content: '复制图片', })
  110. .onClick(() => {
  111. this.result?.copyImage();
  112. this.result?.closeContextMenu();
  113. })
  114. }
  115. }
  116. @Builder
  117. TextMenuBuilder() {
  118. Menu() {
  119. MenuItem({ content: '复制', })
  120. .onClick(() => {
  121. try {
  122. this.controller.runJavaScript(
  123. 'copySelectedText()',
  124. (error, result) => {
  125. if (error) {
  126. console.error(`run copySelectedText JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
  127. return;
  128. }
  129. if (result) {
  130. console.info(`The copySelectedText() return value is: ${result}`);
  131. }
  132. });
  133. } catch (error) {
  134. console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
  135. }
  136. this.clearSelection()
  137. }).backgroundColor(Color.Pink)
  138. }
  139. }
  140. build() {
  141. Column() {
  142. Web({ src: $rawfile("index.html"), controller: this.controller })
  143. .javaScriptAccess(true)
  144. .fileAccess(true)
  145. .onlineImageAccess(true)
  146. .imageAccess(true)
  147. .domStorageAccess(true)
  148. .bindSelectionMenu(WebElementType.TEXT, this.TextMenuBuilder, WebResponseType.LONG_PRESS,
  149. {
  150. onAppear: () => {},
  151. onDisappear: () => {},
  152. menuType: MenuType.SELECTION_MENU,
  153. })
  154. .bindSelectionMenu(WebElementType.LINK, this.LinkMenuBuilder, WebResponseType.LONG_PRESS,
  155. {
  156. onAppear: () => {},
  157. onDisappear: () => {
  158. this.result?.closeContextMenu();
  159. },
  160. preview: this.PreviewBuilder({
  161. width: 500,
  162. height: 400,
  163. url:this.linkURL
  164. }),
  165. menuType: MenuType.PREVIEW_MENU
  166. })
  167. .bindSelectionMenu(WebElementType.IMAGE, this.ImageMenuBuilder, WebResponseType.LONG_PRESS,
  168. {
  169. onAppear: () => {},
  170. onDisappear: () => {
  171. this.result?.closeContextMenu();
  172. },
  173. preview: PreviewBuilderGlobalForImage({
  174. previewImage: this.previewImage,
  175. width: this.previewWidthImage,
  176. height: this.previewHeightImage,
  177. }),
  178. menuType: MenuType.PREVIEW_MENU,
  179. })
  180. .zoomAccess(true)
  181. .onContextMenuShow((event) => {
  182. if (event) {
  183. this.result = event.result;
  184. this.previewWidthImage = this.uiContext!.px2vp(event.param.getPreviewWidth());
  185. this.previewHeightImage = this.uiContext!.px2vp(event.param.getPreviewHeight());
  186. if (event.param.getSourceUrl().indexOf("resource://rawfile/") == 0) {
  187. this.previewImage = $rawfile(event.param.getSourceUrl().substring(19));
  188. } else {
  189. this.previewImage = event.param.getSourceUrl();
  190. }
  191. this.linkURL = event.param.getLinkUrl()
  192. return true;
  193. }
  194. return false;
  195. })
  196. }
  197. }
  198. // 侧滑返回
  199. onBackPress(): boolean | void {
  200. if (this.controller.accessStep(-1)) {
  201. this.controller.backward();
  202. return true;
  203. } else {
  204. return false;
  205. }
  206. }
  207. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html lang="zh-CN">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>长按复制文本</title>
  8. <style>
  9. .container {
  10. background-color: white;
  11. padding: 30px;
  12. margin: 20px 0;
  13. }
  14. .context {
  15. line-height: 1.8;
  16. font-size: 18px;
  17. }
  18. .context span {
  19. border-radius: 8px;
  20. background-color: #f8f9fa;
  21. }
  22. .context a {
  23. color: #3498db;
  24. text-decoration: none;
  25. font-size: 18px;
  26. font-weight: 600;
  27. padding: 12px 24px;
  28. border: 2px solid #3498db;
  29. border-radius: 30px;
  30. display: inline-block;
  31. position: relative;
  32. overflow: hidden;
  33. margin-bottom: 20px;
  34. }
  35. .context img {
  36. max-width: 100%;
  37. height: auto;
  38. display: block;
  39. margin-bottom: 20px;
  40. }
  41. .context:hover img {
  42. transform: scale(1.05);
  43. }
  44. </style>
  45. </head>
  46. <body>
  47. <div class="container">
  48. <div class="context">
  49. <!--img.png为html同目录下图片-->
  50. <img src="img.png">
  51. </div>
  52. <div class="context">
  53. <a href="https://www.example.com">长按链接唤起菜单</a>
  54. </div>
  55. <div class="context">
  56. <span>在这个数字时代,文本复制功能变得日益重要。无论是引用名言、保存重要信息,还是分享有趣的内容,复制文本都是我们日常操作的一部分。</span>
  57. </div>
  58. </div>
  59. <br>
  60. <script>
  61. function copySelectedText() {
  62. const selectedText = window.getSelection().toString();
  63. if (selectedText.length > 0) {
  64. // 使用Clipboard API复制文本
  65. navigator.clipboard.writeText(selectedText)
  66. .then(() => {
  67. showNotification();
  68. })
  69. .catch(err => {
  70. console.error('复制失败:', err);
  71. });
  72. }
  73. }
  74. function clearSelection() {
  75. if (window.getSelection) {
  76. window.getSelection().removeAllRanges();
  77. }
  78. }
  79. </script>
  80. </body>
  81. </html>

blurOnKeyboardHideMode14+

PhonePC/2in1TabletTVWearable

blurOnKeyboardHideMode(mode: BlurOnKeyboardHideMode)

设置当软键盘收起时Web元素失焦模式。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
mode BlurOnKeyboardHideMode 设置当软键盘收起时Web元素失焦关闭或开启。默认值:BlurOnKeyboardHideMode.SILENT。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State blurMode: BlurOnKeyboardHideMode = BlurOnKeyboardHideMode.BLUR;
  8. build() {
  9. Column() {
  10. Web({ src: $rawfile("index.html"), controller: this.controller })
  11. .blurOnKeyboardHideMode(this.blurMode)
  12. }
  13. }
  14. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>测试网页</title>
  6. </head>
  7. <body>
  8. <h1>blurOnKeyboardHideMode Demo</h1>
  9. <input type="text" id="input_a">
  10. <script>
  11. const inputElement = document.getElementById('input_a');
  12. inputElement.addEventListener('blur', function() {
  13. console.info('Input has lost focus');
  14. });
  15. </script>
  16. </body>
  17. </html>

enableFollowSystemFontWeight18+

PhonePC/2in1TabletTVWearable

enableFollowSystemFontWeight(follow: boolean)

设置Web组件是否开启字重跟随系统设置变化。当属性没有显式调用时,Web组件默认字重不跟随系统设置变化。

说明

目前该能力只支持前端文本元素跟随变化,暂不支持canvas元素、内嵌docx和pdf格式中的文本跟随变化。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
follow boolean

设置Web组件是否开启字重跟随系统设置变化。

true表示字重跟随系统设置中的字体粗细变化,系统设置改变时字重跟随变化。false表示字重不再跟随系统设置中的字体粗细变化,系统设置改变时维持当前字重不变。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: "www.example.com", controller: this.controller })
  10. .enableFollowSystemFontWeight(true)
  11. }
  12. }
  13. }

optimizeParserBudget15+

PhonePC/2in1TabletTVWearable

optimizeParserBudget(optimizeParserBudget: boolean)

设置是否开启分段解析HTML优化。当属性没有显式调用时,默认使用解析时间作为HTML分段解析的分段点。

ArkWeb内核在解析HTML文档结构时采取分段解析策略,旨在避免过多占用主线程资源,并使网页具有渐进式加载能力。ArkWeb内核默认使用解析时间作为分段点,当单次解析时间超过阈值时,会中断解析,随后进行布局和渲染操作。

开启优化后,ArkWeb内核将不仅检查解析时间是否超出限制,还会额外判断解析的Token(HTML文档的最小解析单位,例如<div>、attr="xxx"等)数量是否超过内核规定的阈值,并下调此阈值。当页面的FCP(First Contentful Paint 首次内容绘制)触发时会恢复成默认的中断判断逻辑。这将使得网页在FCP到来之前的解析操作更频繁,从而提高首帧内容被提前解析完成并进入渲染阶段的可能性,同时有效缩减首帧渲染的工作量,最终实现FCP时间提前。

由于页面的FCP触发时会恢复成默认分段解析逻辑,因此分段解析HTML优化仅对每个Web组件加载的首个页面生效。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
optimizeParserBudget boolean

设置开启分段解析HTML优化。

true表示使用解析个数代替解析时间作为HTML分段解析的分段点,并减少每段解析的个数上限。false表示使用解析时间作为HTML分段解析的分段点。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController()
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .optimizeParserBudget(true)
  11. }
  12. }
  13. }

enableWebAVSession18+

PhonePC/2in1TabletTVWearable

enableWebAVSession(enabled: boolean)

设置是否支持应用对接到播控中心。当属性没有显式设置时,默认支持应用对接到播控中心。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
enabled boolean

设置是否支持应用对接到播控中心。

true表示支持应用对接到播控中心,false表示不支持应用对接到播控中心。

传入undefined或null时为true。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile('index.html'), controller: this.controller })
  10. .enableWebAVSession(true)
  11. }
  12. }
  13. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>视频播放页面</title>
  6. </head>
  7. <body>
  8. <h1>视频播放</h1>
  9. <video id="testVideo" controls>
  10. <!--在resources的rawfile目录中放置任意一个mp4媒体文件,并将其命名为example.mp4-->
  11. <source src="example.mp4" type="video/mp4">
  12. </video>
  13. </body>
  14. </html>

nativeEmbedOptions16+

PhonePC/2in1TabletTVWearable

nativeEmbedOptions(options?: EmbedOptions)

设置同层渲染相关配置,该属性仅在enableNativeEmbedMode开启时生效,不支持动态修改。当属性没有显式调用时,默认为{supportDefaultIntrinsicSize: false}。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
options EmbedOptions

同层渲染相关配置。

传入undefined或null时为{supportDefaultIntrinsicSize: false}。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. options: EmbedOptions = {supportDefaultIntrinsicSize: true};
  8. build() {
  9. Column() {
  10. Web({ src: $rawfile("index.html"), controller: this.controller })
  11. .enableNativeEmbedMode(true)
  12. .nativeEmbedOptions(this.options)
  13. }
  14. }
  15. }

加载的html文件

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>同层渲染固定大小测试html</title>
  6. </head>
  7. <body>
  8. <div>
  9. <embed id="input" type = "native/view" style = "background-color:red"/>
  10. </div>
  11. </body>
  12. </html>

enableDataDetector20+

PhonePC/2in1TabletTVWearable

enableDataDetector(enable: boolean)

设置是否识别网页文本特殊实体,如邮件、电话、网址等。该接口依赖设备底层具备文本识别能力,否则设置无效。该属性没有显式调用时,默认不启用。

当enableDataDetector设置为true,同时不设置dataDetectorConfig属性时,默认识别所有类型的实体,所识别实体的color和decoration会被更改为如下样式:

收起
自动换行
深色代码主题
复制
  1. color: '#ff0a59f7',
  2. decoration:{
  3. type: TextDecorationType.Underline,
  4. color: '#ff0a59f7',
  5. style: TextDecorationStyle.SOLID
  6. }

当enableDataDetector设置为true且copyOptions设置为CopyOptions.LocalDevice时,AI菜单功能将被激活。此时,在网页中选中文本后,文本选择菜单能够展示对应的AI菜单项,包括TextMenuItemId中的url(打开链接)、email(新建邮件)、phoneNumber(呼叫)、address(导航至该位置)、dateTime(新建日程提醒)。

AI菜单生效时,需在选中范围内,包括一个完整的AI实体,才能展示对应的选项。该菜单项与TextMenuItemId中的askAI菜单项不同时出现。

示例使用场景详见使用Web组件的智能分词能力

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
enable boolean

是否启用Web文本识别,true表示启用,false表示不启用。

传入undefined或null时属性设置不生效。

说明

动态更新enableDataDetector的启用状态不会即时影响当前页面,需通过刷新页面来使新配置生效。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile("index.html"), controller: this.controller })
  10. .enableDataDetector(true)
  11. }
  12. }
  13. }

加载的html文件

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>enableDataDetector示例</title>
  6. </head>
  7. <body>
  8. <p> 电话:400-123-4567 </p>
  9. <p> 邮箱:example@example.com </p>
  10. </body>
  11. </html>

dataDetectorConfig20+

PhonePC/2in1TabletTVWearable

dataDetectorConfig(config: TextDataDetectorConfig)

设置文本识别配置。

需配合enableDataDetector一起使用,设置enableDataDetector为true时,dataDetectorConfig的配置才能生效。

当两个实体A、B重叠时,按以下规则保留实体:

  1. 若A ⊂ B,则保留B,反之则保留A。

  2. 当A ⊄ B且B ⊄ A时,若A.start < B.start,则保留A,反之则保留B。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
config TextDataDetectorConfig 文本识别配置。
说明

TextDataDetectorConfig中的onDetectResultUpdate在Web组件中不支持,设置的回调不会调用。

copyOptions设置为CopyOptions.None时,TextDataDetectorConfig中的enablePreviewMenu配置项无效。

动态更新TextDataDetectorConfig的配置不会即时影响当前页面,需通过刷新页面来使新配置生效。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile("index.html"), controller: this.controller })
  10. .enableDataDetector(true)
  11. .dataDetectorConfig({
  12. types: [
  13. TextDataDetectorType.PHONE_NUMBER,
  14. TextDataDetectorType.EMAIL
  15. ],
  16. color: Color.Red,
  17. decoration: {
  18. type: TextDecorationType.LineThrough,
  19. color: Color.Green,
  20. style: TextDecorationStyle.WAVY
  21. }
  22. })
  23. }
  24. }
  25. }

加载的html文件

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>dataDetectorConfig示例</title>
  6. </head>
  7. <body>
  8. <p> 电话:400-123-4567 </p>
  9. <p> 邮箱:12345678901@example.com </p>
  10. <p> 网址:www.example.com(此项不识别)</p>
  11. </body>
  12. </html>

enableSelectedDataDetector22+

PhonePC/2in1TabletTVWearable

enableSelectedDataDetector(enable: boolean)

设置是否启用文本选择的AI菜单功能,启用后可识别选区中的邮件、电话、网址、日期、地址等,并在文本选择菜单中展示对应的AI菜单项。默认启用AI菜单功能。

AI菜单功能启用时,在网页中选中文本后,文本选择菜单能够展示对应的AI菜单项,包括TextMenuItemId中的url(打开链接)、email(新建邮件)、phoneNumber(呼叫)、address(导航前往)、dateTime(新建日程)。

AI菜单生效时,需在选中范围内,包括一个完整的AI实体,才能展示对应的选项。该菜单项与TextMenuItemId中的askAI菜单项不同时出现。

示例使用场景详见使用Web组件的智能分词能力

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
enable boolean

是否启用Web文本识别,true表示启用,false表示不启用。

传入undefined或null时属性重置为默认值。

说明

当enableSelectedDataDetector未配置或设置为true时,将遵循dataDetectorConfig中types的配置;若dataDetectorConfig也未配置,则默认识别所有类型。

当enableSelectedDataDetector设置为false时,不激活实体文本选择AI菜单项。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile("index.html"), controller: this.controller })
  10. .enableSelectedDataDetector(true)
  11. }
  12. }
  13. }

加载的html文件

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>enableSelectedDataDetector示例</title>
  6. </head>
  7. <body>
  8. <p> 电话:400-123-4567 </p>
  9. <p> 邮箱:example@example.com </p>
  10. </body>
  11. </html>

gestureFocusMode20+

PhonePC/2in1TabletTVWearable

gestureFocusMode(mode: GestureFocusMode)

设置Web组件手势获焦模式。该属性没有显式调用时,默认表示手势按下时,任何手势均会使Web组件获焦。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
mode GestureFocusMode 设置Web组件手势获焦模式。传入undefined或null时为GestureFocusMode.DEFAULT。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State mode: GestureFocusMode = GestureFocusMode.DEFAULT;
  8. build() {
  9. Column() {
  10. Web({ src: $rawfile("index.html"), controller: this.controller })
  11. .gestureFocusMode(this.mode)
  12. }
  13. }
  14. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>测试网页</title>
  6. </head>
  7. <body>
  8. <input type="text" placeholder="Text">
  9. </body>
  10. </html>

rotateRenderEffect22+

PhonePC/2in1TabletTVWearable

rotateRenderEffect(effect: WebRotateEffect)

设置Web组件旋转时,宽高动画过程中组件内容的填充方式。若未显式调用属性,默认保持动画终态的内容大小,内容始终与组件左上角对齐。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
effect WebRotateEffect 设置Web组件旋转时,宽高动画过程中组件内容的填充方式。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State effect: WebRotateEffect = WebRotateEffect.TOPLEFT_EFFECT;
  8. build() {
  9. Column() {
  10. Web({ src: $rawfile("index.html"), controller: this.controller })
  11. .rotateRenderEffect(this.effect)
  12. }
  13. }
  14. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>测试网页</title>
  6. </head>
  7. <body>
  8. <p>测试网页</p>
  9. </body>
  10. </html>

forceEnableZoom21+

PhonePC/2in1TabletTVWearable

forceEnableZoom(enable: boolean)

设置Web组件是否启用强制缩放功能。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
enable boolean

设置是否遵从网页中<meta name="viewport">标签设置的缩放限制。

设置为true时,不遵从网页缩放限制;设置为false时,遵从网页缩放限制。

传入undefined与null时属性设置不生效。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile("index.html"), controller: this.controller })
  10. .forceEnableZoom(true)
  11. }
  12. }
  13. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
  6. <title>测试网页</title>
  7. </head>
  8. <body>
  9. <h1>forceEnableZoom Demo</h1>
  10. <span>You can scale page when forceEnableZoom is true.</span>
  11. </body>
  12. </html>

backToTop22+

PhonePC/2in1TabletTVWearable

backToTop(backToTop: boolean)

设置Web组件是否启用点击状态栏网页回到顶部功能。当属性没有显式调用时,默认开启状态栏网页回到顶部功能。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
backToTop boolean

是否启用Web点击状态栏回顶,true表示启用,false表示不启用。

传入undefined或null时为true。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile("index.html"), controller: this.controller })
  10. .backToTop(true)
  11. }
  12. }
  13. }

加载的html文件:

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0">
  6. <style>
  7. .blue {
  8. background-color: lightblue;
  9. }
  10. .green {
  11. background-color: lightgreen;
  12. }
  13. .blue, .green {
  14. font-size:16px;
  15. height:200px;
  16. text-align: center; /* 水平居中 */
  17. line-height: 200px; /* 垂直居中(值等于容器高度) */
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <div class="blue" >webArea</div>
  23. <div class="green">webArea</div>
  24. <div class="blue">webArea</div>
  25. <div class="green">webArea</div>
  26. <div class="blue">webArea</div>
  27. <div class="green">webArea</div>
  28. <div class="blue">webArea</div>
  29. <div class="green">webArea</div>
  30. <div class="blue">webArea</div>
  31. </body>
  32. </html>

blankScreenDetectionConfig22+

PhonePC/2in1TabletTVWearable

blankScreenDetectionConfig(detectConfig: BlankScreenDetectionConfig)

设置白屏检测的策略配置,如使能开关、检测时间和检测策略等。当属性没有显式调用时,默认关闭白屏检测。

说明
  • 根据detectConfig的配置,在网页加载后检测到白屏或者近似白屏现象,可触发回调onDetectedBlankScreen
  • 设置后下次导航生效。
  • 当用户与网页发生交互后,不再会继续检查是否白屏。
  • 不支持layoutMode为WebLayoutMode.FIT_CONTENT的场景。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
detectConfig BlankScreenDetectionConfig 白屏检测的策略配置。

示例:

收起
自动换行
深色代码主题
复制
  1. // blankScreenDetectionConfig.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .blankScreenDetectionConfig({
  11. enable: true,
  12. detectionTiming: [2, 4, 6, 8],
  13. contentfulNodesCountThreshold: 4,
  14. detectionMethods:[BlankScreenDetectionMethod.DETECTION_CONTENTFUL_NODES_SEVENTEEN]
  15. })
  16. .onDetectedBlankScreen((event: BlankScreenDetectionEventInfo)=>{
  17. console.info(`Found blank screen on ${event.url}.`);
  18. console.info(`The blank screen reason is ${event.blankScreenReason}.`);
  19. console.info(`The blank screen detail is ${event.blankScreenDetails?.detectedContentfulNodesCount}.`);
  20. })
  21. }
  22. }
  23. }

enableImageAnalyzer23+

PhonePC/2in1TabletTVWearable

enableImageAnalyzer(enable: boolean)

设置是否启用网页图片AI分析,当前支持图片文字识别功能。属性未显式调用时,该功能默认开启。

说明

长按或鼠标悬停在图片文字上时,触发图片AI分析,可以选中图片中的文字。能够触发分析的图片规格如下。

  • 图片的原始长宽均不小于100px。

  • 设备类型不为2in1的设备上,需要图片渲染宽度超过网页宽度的80%。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
enable boolean

是否启用网页图片AI分析,true表示启用,false表示不启用。

传入undefined或null时重置为true。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile("index.html"), controller: this.controller })
  10. .enableImageAnalyzer(true) // 如果需要关闭图片分析能力,需要显式设置为false
  11. }
  12. }
  13. }

加载的html文件:

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0">
  6. <style>
  7. .image-container {
  8. width: 90%;
  9. }
  10. .image-container img {
  11. width: 100%;
  12. height: auto;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <div class="image-container">
  18. <!--example.jpg为html同目录下图片-->
  19. <img src="example.jpg" alt="待AI分析的图片">
  20. </div>
  21. </body>
  22. </html>

enableAutoFill23+

PhonePC/2in1TabletTVWearable

enableAutoFill(value: boolean)

设置是否启用网页自动填充,默认开启。

说明

网页使用智能填充和密码填充前,需要网页接入对应的填充服务。具体接入方法请查看网页接入智能填充网页接入密码填充

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
value boolean

是否启用网页自动填充,true表示启用,false表示不启用。

传入undefined或null时为true。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile("index.html"), controller: this.controller })
  10. .enableAutoFill(true)
  11. }
  12. }
  13. }

加载的html文件:

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport"/>
  6. <title>自动填充测试</title>
  7. </head>
  8. <body>
  9. <h4 align="center">自动填充测试</h4>
  10. <form method="post" action="">
  11. <div align="center">
  12. <label for="name" style="width: 120px; display: inline-block; text-align: end;">姓名:</label>
  13. <input type="text" id="name" autocomplete="name"/><br/><br/>
  14. <label for="tel-national" style="width: 120px; display: inline-block; text-align: end;">手机号:</label>
  15. <input type="text" id="tel-national" autocomplete="tel-national"/><br/><br/>
  16. </div>
  17. <div align="center">
  18. <button type="submit" style="width: 80px">提交</button>
  19. </div>
  20. </form>
  21. </body>
  22. </html>

enableDefaultContextMenu24+

PhonePC/2in1TabletTVWearable

enableDefaultContextMenu(enable: boolean)

设置是否启用默认右键上下文菜单。不调用该方法时,默认不启用。默认菜单仅支持CUT、COPY、PASTE、SELECT_ALL菜单项。

说明
  • 当设置了onContextMenuShow回调并在回调中返回true时,本接口的设置不生效。
  • 默认菜单项会受editMenuOptions控制,通过该属性可以自定义菜单选项。

模型约束: 此接口仅可在Stage模型下使用。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
enable boolean

是否启用默认右键上下文菜单,true表示启用,false表示不启用。

传入undefined或null时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .enableDefaultContextMenu(true)
  11. }
  12. }
  13. }

enableDragBeta

PhonePC/2in1TabletTVWearable

enableDrag(value: boolean)

设置是否启用拖拽功能。不调用该属性时,默认启用网页拖拽功能。

起始版本: 26.0.0

模型约束: 此接口仅可在Stage模型下使用。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
value boolean 是否启用网页拖拽功能,true表示启用,false表示不启用。
示例:
收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct Index {
  6. private controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile('test.html'), controller: this.controller })
  10. .enableDrag(false)
  11. }
  12. }
  13. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--test.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head><meta charset="UTF-8"><title>拖拽测试</title></head>
  5. <body>
  6. <div id="drag" draggable="true" style="width:100px;height:100px;background:red;margin:20px;"></div>
  7. <div id="drop" style="width:200px;height:200px;background:gray;margin:20px;"></div>
  8. <script>
  9. drag.ondragstart=e=>e.dataTransfer.setData('text/plain','');
  10. drop.ondragover=e=>e.preventDefault();
  11. drop.ondrop=e=>{e.preventDefault(); drop.style.background='green';};
  12. drag.ondragend=()=>{drop.style.background='gray';};
  13. </script>
  14. </body>
  15. </html>

password(deprecated)

PhonePC/2in1TabletTVWearable

password(password: boolean)

设置是否应保存密码。该接口为空接口。

说明

从API version 8开始支持,从API version 10开始废弃,建议使用enableAutoFill23+替代。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
password boolean

设置为true时,表示允许Web保存密码。

设置为false时,表示不允许Web保存密码。

textZoomAtio(deprecated)

PhonePC/2in1TabletTVWearable

textZoomAtio(textZoomAtio: number)

设置页面的文本缩放百分比。

说明

从API version 8开始支持,从API version 9开始废弃,建议使用textZoomRatio9+代替。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
textZoomAtio number

要设置的页面的文本缩放百分比。

取值范围为正整数。

默认值:100。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct WebComponent {
  5. controller: WebController = new WebController()
  6. @State ratio: number = 150
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .textZoomAtio(this.ratio)
  11. }
  12. }
  13. }

userAgent(deprecated)

PhonePC/2in1TabletTVWearable

userAgent(userAgent: string)

设置用户代理。

说明

从API version 8开始支持,从API version 10开始废弃。建议使用setCustomUserAgent10+替代。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
userAgent string 要设置的用户代理。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State userAgent:string = 'Mozilla/5.0 (Phone; OpenHarmony 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 ArkWeb/4.1.6.1 Mobile DemoApp';
  8. build() {
  9. Column() {
  10. Web({ src: 'www.example.com', controller: this.controller })
  11. .userAgent(this.userAgent)
  12. }
  13. }
  14. }

tableData(deprecated)

PhonePC/2in1TabletTVWearable

tableData(tableData: boolean)

设置是否应保存表单数据。当属性没有显式调用时,默认允许Web保存表单数据。该接口为空接口。

说明

从API version 8开始支持,从API version 10开始废弃,建议使用enableAutoFill23+替代。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
tableData boolean

设置为true时,表示允许Web保存表单数据。

设置为false时,表示不允许Web保存表单数据。

wideViewModeAccess(deprecated)

PhonePC/2in1TabletTVWearable

wideViewModeAccess(wideViewModeAccess: boolean)

设置Web是否支持html中meta标签的viewport属性。该接口为空接口。

说明

从API version 8开始支持,从API version 10开始废弃,建议使用metaViewport12+替代。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
wideViewModeAccess boolean

设置Web是否支持html中meta标签的viewport属性。

true表示支持html中meta标签的viewport属性,false表示不支持html中meta标签的viewport属性。

selectionMenuOptions(deprecated)

PhonePC/2in1TabletTVWearable

selectionMenuOptions(expandedMenuOptions: Array<ExpandedMenuItemOptions>)

Web组件自定义菜单扩展项接口,允许用户设置扩展项的文本内容、图标、回调方法。

该接口只支持选中纯文本,当选中内容包含图片及其他非文本内容时,action信息中会显示乱码。

说明

从API version 12开始支持,从API version 20开始废弃。建议使用editMenuOptions12+替代。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
expandedMenuOptions Array<ExpandedMenuItemOptions>

扩展菜单选项。

菜单项数量,及菜单的content大小、startIcon图标尺寸,与ArkUI Menu组件保持一致。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State menuOptionArray: Array<ExpandedMenuItemOptions> = [
  8. {content: 'Apple', startIcon: $r('app.media.icon'), action: (selectedText) => {
  9. console.info('select info ' + selectedText.toString());
  10. }},
  11. {content: '香蕉', startIcon: $r('app.media.icon'), action: (selectedText) => {
  12. console.info('select info ' + selectedText.toString());
  13. }}
  14. ];
  15. build() {
  16. Column() {
  17. Web({ src: $rawfile("index.html"), controller: this.controller })
  18. .selectionMenuOptions(this.menuOptionArray)
  19. }
  20. }
  21. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>测试网页</title>
  6. </head>
  7. <body>
  8. <h1>selectionMenuOptions Demo</h1>
  9. <span>selection menu options</span>
  10. </body>
  11. </html>

zoomControlAccess22+

PhonePC/2in1TabletTVWearable

zoomControlAccess(zoomControlAccess: boolean)

设置是否允许通过组合按键(Ctrl+'-/+'或Ctrl+鼠标滚轮/触摸板)进行缩放。

当属性没有显式调用时,默认允许通过组合按键进行缩放。

系统能力: SystemCapability.Web.Webview.Core

参数:

展开
参数名 类型 必填 说明
zoomControlAccess boolean 设置是否允许通过组合按键进行缩放。true表示支持,false表示不支持。传入null或undefined时为false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: $rawfile("index.html"), controller: this.controller })
  10. .zoomControlAccess(true)
  11. }
  12. }
  13. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>测试网页</title>
  7. </head>
  8. <body>
  9. <h1>zoomControlAccess Demo</h1>
  10. <span>You can zoom in/out page when zoomControlAccess is true.</span>
  11. </body>
  12. </html>

aiSessionOptionsBeta

PhonePC/2in1TabletTVWearable

aiSessionOptions(aiSessions: Array<AISessionEvent>)

自定义Web组件的前端AI会话配置,用于注册多个自定义AI会话。

系统能力: SystemCapability.Web.Webview.Core

起始版本: 26.0.0

模型约束: 此接口仅可在Stage模型下使用。

参数:

展开
参数名 类型 必填 说明
aiSessions Array<AISessionEvent> 前端AI会话配置对象数组,每个对象包含AI会话类型及对应的生命周期回调方法。当前仅支持AISessionType中包含的模型。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct DemoPage {
  6. private webController: webview.WebviewController = new webview.WebviewController();
  7. sessions: Map<string, string> = new Map<string, string>();
  8. onCreateAISession = (id: string, params: string, result: OnAISessionCallback): boolean => {
  9. this.sessions.set(id, params); // 模拟创建AI会话
  10. console.info(`[AISession]onCreateAISession params: ${params}`);
  11. result(AISessionResultType.SUCCESS, "AISession created");
  12. return true;
  13. }
  14. onExecuteAIAction = (id: string, params: string, result: OnAISessionCallback): void => {
  15. this.sessions.get(id); // 模拟取出会话,并执行动作
  16. console.info(`[AISession]onExecuteAIAction params: ${params}`);
  17. result(AISessionResultType.RUNNING, "AISession chunk 1\n");
  18. result(AISessionResultType.RUNNING, "AISession chunk 2\n");
  19. result(AISessionResultType.SUCCESS, "AISession chunk end\n");
  20. }
  21. onDestroyAISession = (id: string): void => {
  22. this.sessions.delete(id); // 模拟销毁会话并释放资源
  23. }
  24. @State options: AISessionEvent = {
  25. aiSessionType: AISessionType.SUMMARIZER,
  26. onCreateAISession: this.onCreateAISession,
  27. onExecuteAIAction: this.onExecuteAIAction,
  28. onDestroyAISession: this.onDestroyAISession
  29. }
  30. build() {
  31. Column() {
  32. Web({ src: $rawfile('index.html'), controller: this.webController })
  33. .aiSessionOptions([this.options])
  34. }
  35. .width('100%')
  36. .height('100%')
  37. }
  38. }

加载的html文件

收起
自动换行
深色代码主题
复制
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width,initial-scale=1.0">
  6. <title>Summarizer API Test</title>
  7. </head>
  8. <body style="max-width:600px;margin:20px auto;padding:0 16px;">
  9. <p id="status">checking...</p>
  10. <button id="initBtn" onclick="init()">Create Session</button>
  11. <br><br>
  12. <textarea id="input" rows="6" style="width:100%;font:inherit" placeholder="paste text to summarize"></textarea>
  13. <br><br>
  14. <button id="btn" onclick="run()" disabled>Summarize</button>
  15. <pre id="result"></pre>
  16. <script>
  17. let s;
  18. (async () => {
  19. const d = document.getElementById('status');
  20. if (!('Summarizer' in self)) { d.textContent = 'API not supported'; return; }
  21. const a = await Summarizer.availability();
  22. d.textContent = 'Summarizer: ' + a;
  23. if (a === 'unavailable') document.getElementById('initBtn').disabled = true;
  24. })();
  25. async function init() {
  26. const d = document.getElementById('status'), ib = document.getElementById('initBtn');
  27. ib.disabled = true;
  28. d.textContent = 'creating...';
  29. try {
  30. s = await Summarizer.create({
  31. type: 'tldr', length: 'medium', format: 'plain-text',
  32. monitor(m) { m.addEventListener('downloadprogress', e => { d.textContent = 'downloading ' + (e.loaded * 100 | 0) + '%' }); }
  33. });
  34. d.textContent = 'ready';
  35. document.getElementById('btn').disabled = false;
  36. } catch (e) { d.textContent = 'Error: ' + e.message; ib.disabled = false; }
  37. }
  38. async function run() {
  39. const t = document.getElementById('input').value.trim();
  40. if (!t || !s) return;
  41. const btn = document.getElementById('btn'), r = document.getElementById('result');
  42. btn.disabled = true;
  43. r.textContent = '...';
  44. try { r.textContent = await s.summarize(t); }
  45. catch (e) { r.textContent = 'Error: ' + e.message; }
  46. btn.disabled = false;
  47. }
  48. </script>
  49. </body>
  50. </html>

scrollbarLayoutPolicyBeta

PhonePC/2in1TabletTVWearable

scrollbarLayoutPolicy(policy: ScrollbarLayoutPolicy)

选择Web组件内垂直滚动条的布局方式。

系统能力: SystemCapability.Web.Webview.Core

模型约束: 此接口仅可在Stage模型下使用。

起始版本: 26.0.0

参数:

展开
参数名 类型 必填 说明
policy ScrollbarLayoutPolicy

设置Web组件内垂直滚动条布局模式,可选择跟随系统语言方向设置或网页css的direction属性设置。入参设置为:

CONTENT,表示跟随网页css的direction属性设置。

SYSTEM,滚动条会根据系统语种的左右书写方向进行布局。对于从右向左书写的语言,滚动条将布局在左侧。对于网页内嵌套的多层滚动条均适用。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .width('100%')
  11. .height('100%')
  12. // 设置为SYSTEM表示跟随系统语言方向布局。设置为CONTENT表示沿用Web样式布局
  13. .scrollbarLayoutPolicy(ScrollbarLayoutPolicy.SYSTEM)
  14. }
  15. }
  16. }

keyboardAppearanceBeta

PhonePC/2in1TabletTVWearable

keyboardAppearance(mode: WebKeyboardAppearanceMode)

设置键盘外观。不调用该方法时,默认跟随系统的沉浸式模式。

系统能力: SystemCapability.Web.Webview.Core

模型约束: 此接口仅可在Stage模型下使用。

起始版本: 26.0.0

参数:

展开
参数名 类型 必填 说明
mode WebKeyboardAppearanceMode 键盘外观。传入undefined或null时,跟随系统的沉浸式模式。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. @State appearanceMode: WebKeyboardAppearanceMode = WebKeyboardAppearanceMode.DARK_IMMERSIVE;
  8. build() {
  9. Column() {
  10. Web({ src: $rawfile("index.html"), controller: this.controller })
  11. .keyboardAppearance(this.appearanceMode)
  12. }
  13. }
  14. }

加载的html文件。

收起
自动换行
深色代码主题
复制
  1. <!--index.html-->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>测试网页</title>
  6. </head>
  7. <body>
  8. <input type="text" placeholder="Text">
  9. </body>
  10. </html>

enableFullscreenVideoOverlayBeta

PhonePC/2in1TabletTVWearable

enableFullscreenVideoOverlay(enabled: boolean)

设置Web组件是否开启覆盖式全屏播放功能。当属性没有显式调用时,默认不开启该能力。

说明
  • 当前只支持H264、H265解码格式的视频。
  • 只有视频元素发出的全屏请求才会响应。

起始版本: 26.0.0

系统能力: SystemCapability.Web.Webview.Core

模型约束: 此接口仅可在Stage模型下使用。

设备行为差异: 该接口在PC/2in1设备中无效果,在其他设备中可正常调用。

参数:

展开
参数名 类型 必填 说明
enabled boolean

设置Web组件是否开启覆盖式全屏播放功能。

true表示开启该功能。

false表示不开启。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. import { webview } from '@kit.ArkWeb';
  3. @Entry
  4. @Component
  5. struct WebComponent {
  6. controller: webview.WebviewController = new webview.WebviewController();
  7. build() {
  8. Column() {
  9. Web({ src: 'www.example.com', controller: this.controller })
  10. .enableFullscreenVideoOverlay(true)
  11. }
  12. }
  13. }
在 API参考 中进行搜索
请输入您想要搜索的关键词