0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

鴻蒙ArkTS聲明式組件:Web

jf_46214456 ? 來源:jf_46214456 ? 作者:jf_46214456 ? 2024-07-04 15:35 ? 次閱讀

Web

提供具有網(wǎng)頁顯示能力的Web組件,[@ohos.web.webview]提供web控制能力。

說明:
開發(fā)前請熟悉鴻蒙開發(fā)指導文檔 :[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md]

  • 該組件從API Version 8開始支持。后續(xù)版本如有新增內(nèi)容,則采用上角標單獨標記該內(nèi)容的起始版本。
  • 示例效果請以真機運行為準,當前IDE預(yù)覽器不支持。

需要權(quán)限

ArkUI:

訪問在線網(wǎng)頁時需添加網(wǎng)絡(luò)權(quán)限:ohos.permission.INTERNET。

Android:

訪問在線網(wǎng)頁時需添加網(wǎng)絡(luò)權(quán)限:android.permission.INTERNET

iOS:

無需設(shè)置,應(yīng)用通過詢問用戶獲取網(wǎng)絡(luò)權(quán)限。

跨平臺相關(guān)設(shè)置

無法訪問Http的設(shè)置

Android

targetSdkVersion版本升級到28之后,默認拒絕應(yīng)用程序使用明文流量的請求,如http協(xié)議不再支持訪問。 需要在AndroidManifest.xml中開啟明文網(wǎng)絡(luò)流量解決此問題

android:usesCleartextTraffic="true"

如需詳細網(wǎng)絡(luò)安全設(shè)置也可以通過配置android:networkSecurityConfig屬性來進行詳細設(shè)置。

iOS

App Transport Security (ATS) 不支持訪問http服務(wù)。通過修改info.plist可以做到。

在源代碼模式修改比較方便。 在Xcode中右擊項目中的info.plist,選擇Open As > Source Code,在plist標簽中加入NSAppTransportSecurity。

示例如下:

< plist version="1.0" >
< dict >
	< key >NSAppTransportSecurity< /key >
	< dict >
		< key >NSAllowsArbitraryLoads< /key >
		< true/ >
	< /dict >
< /dict >
< /plist >

子組件

接口

Web(options: { src: ResourceStr, controller: WebviewController})

說明:

不支持轉(zhuǎn)場動畫。 同一頁面的多個web組件,必須綁定不同的WebviewController。

參數(shù)

參數(shù)名參數(shù)類型必填參數(shù)描述
src[ResourceStr]網(wǎng)頁資源地址。如果訪問本地資源文件,請使用$rawfile。
controller[WebviewController9+]控制器

示例:

加載在線網(wǎng)頁

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
    }
  }
}

加載本地網(wǎng)頁

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  build() {
    Column() {
      // 通過$rawfile加載本地資源文件。
      Web({ src: $rawfile("index.html"), controller: this.controller })
    }
  }
}

加載的index.html文件,位于resources目錄下rawfile子目錄中

< !-- index.html -- >
< !DOCTYPE html >
< html >
    < body >
        < p >Hello World< /p >
    < /body >
< /html >

屬性

javaScriptAccess

javaScriptAccess(javaScriptAccess: boolean)

設(shè)置是否允許執(zhí)行JavaScript腳本,默認允許執(zhí)行。

參數(shù):

參數(shù)名參數(shù)類型必填默認值參數(shù)描述
javaScriptAccessbooleantrue是否允許執(zhí)行JavaScript腳本。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
        .javaScriptAccess(true)
    }
  }
}

zoomAccess

zoomAccess(zoomAccess: boolean)

設(shè)置是否支持手勢進行縮放,默認允許執(zhí)行縮放。

參數(shù):

參數(shù)名參數(shù)類型必填默認值參數(shù)描述
zoomAccessbooleantrue設(shè)置是否支持手勢進行縮放。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
        .zoomAccess(true)
    }
  }
}

onPageBegin

onPageBegin(callback: (event?: { url: string }) => void)

網(wǎng)頁開始加載時觸發(fā)該回調(diào),且只在主frame觸發(fā),iframe或者frameset的內(nèi)容加載時不會觸發(fā)此回調(diào)。
Android和iOS的觸發(fā)時機與OpenHarmony不完全相同,以各平臺行為為準。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
urlstring頁面的URL地址。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()

  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
        .onPageBegin((event) = > {
          if (event) {
            console.log('url:' + event.url)
          }
        })
    }
  }
}

onPageEnd

onPageEnd(callback: (event?: { url: string }) => void)

網(wǎng)頁加載完成時觸發(fā)該回調(diào),且只在主frame觸發(fā)。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
urlstring頁面的URL地址。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()

  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
        .onPageEnd((event) = > {
          if (event) {
            console.log('url:' + event.url)
          }
        })
    }
  }
}

onErrorReceive

onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResourceError }) => void)

網(wǎng)頁加載遇到錯誤時觸發(fā)該回調(diào)。出于性能考慮,建議此回調(diào)中盡量執(zhí)行簡單邏輯。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
request[WebResourceRequest]網(wǎng)頁請求的封裝信息。
error[WebResourceError]網(wǎng)頁加載資源錯誤的封裝信息 。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()

  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
        .onErrorReceive((event) = > {
          if (event) {
            console.log('getErrorInfo:' + event.error.getErrorInfo())
            console.log('getErrorCode:' + event.error.getErrorCode())
            console.log('url:' + event.request.getRequestUrl())
          }
        })
    }
  }
}

minFontSize9+

minFontSize(size: number)

設(shè)置網(wǎng)頁字體大小最小值。

參數(shù):

參數(shù)名參數(shù)類型必填默認值參數(shù)描述
sizenumber8設(shè)置網(wǎng)頁字體大小最小值,單位px。輸入值的范圍為-2^31到2^31-1,實際渲染時超過72的值按照72進行渲染,低于1的值按照1進行渲染。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  @State fontSize: number = 30
  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
        .minFontSize(this.fontSize)
    }
  }
}

horizontalScrollBarAccess9+

horizontalScrollBarAccess(horizontalScrollBar: boolean)

設(shè)置是否顯示橫向滾動條,包括系統(tǒng)默認滾動條和用戶自定義滾動條。默認顯示。

參數(shù):

參數(shù)名參數(shù)類型必填默認值參數(shù)描述
horizontalScrollBarbooleantrue設(shè)置是否顯示橫向滾動條。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
    
  build() {
    Column() {
      Web({ src: $rawfile('index.html'), controller: this.controller })
      .horizontalScrollBarAccess(true).height(150).width(200)
    }
  }
}

加載的html文件。

< !--index.html-- >
< !DOCTYPE html >
< html >
  < head >
    < title >Demo< /title >
    < style >
      body {
        width:3000px;
        height:3000px;
        padding-right:170px;
        padding-left:170px;
        border:5px solid blueviolet
      }
    < /style >
  < /head >
  < body >
    Scroll Test
  < /body >
< /html >

verticalScrollBarAccess9+

verticalScrollBarAccess(verticalScrollBar: boolean)

設(shè)置是否顯示縱向滾動條,包括系統(tǒng)默認滾動條和用戶自定義滾動條。默認顯示。

參數(shù):

參數(shù)名參數(shù)類型必填默認值參數(shù)描述
verticalScrollBarAccessbooleantrue設(shè)置是否顯示縱向滾動條。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new w eb_webview.WebviewController()

  build() {
    Column() {
      Web({ src: $rawfile('index.html'), controller: this.controller })
      .verticalScrollBarAccess(true).height(150).width(200)
    }
  }
}

加載的html文件。

< !--index.html-- >
< !DOCTYPE html >
< html >
  < head >
    < title >Demo< /title >
    < style >
      body {
        width:3000px;
        height:3000px;
        padding-right:170px;
        padding-left:170px;
        border:5px solid blueviolet
      }
    < /style >
  < /head >
  < body >
    Scroll Test
  < /body >
< /html >

backgroundColor

backgroundColor(ResourceColor:Color | number | string)

設(shè)置web組件背景顏色

參數(shù):

ResourceColor

類型說明
[Color]顏色枚舉值。
numberHEX格式顏色,支持rgb。示例:0xffffff。
stringrgb或者argb格式顏色。示例:'#ffffff', '#ff000000', 'rgb(255, 100, 255)', 'rgba(255, 100, 255, 0.5)'。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
controller1: web_webview.WebviewController = new web_webview.WebviewController();
controller2: web_webview.WebviewController = new web_webview.WebviewController();
controller3: web_webview.WebviewController = new web_webview.WebviewController();
controller4: web_webview.WebviewController = new web_webview.WebviewController();

build() {
  Column() {
    Text('設(shè)置backgroundColor為Color.Blue').height(50)
    Web({ src: 'https://www.example.com', controller: this.controller1 })
      .backgroundColor(Color.Blue).height(200)
      
    Text('設(shè)置backgroundColor為0x00ffff').height(50)
    Web({ src: 'https://www.example.com', controller: this.controller2 })
      .backgroundColor(0x00ffff).height(200)
      
    Text('設(shè)置backgroundColor為"#00FF00"').height(50)
    Web({ src: 'https://www.example.com', controller: this.controller3 })
      .backgroundColor('#00FF00').height(200)
      
    Text('設(shè)置backgroundColor為"rgb(255, 100, 255)"').height(50)
    Web({ src: 'https://www.example.com', controller: this.controller4 })
      .backgroundColor('rgb(255, 100, 255)').height(200)
  }
}
}

mediaPlayGestureAccess

mediaPlayGestureAccess(access: boolean)

設(shè)置有聲視頻播放是否需要用戶手動點擊,靜音視頻播放不受該接口管控,默認需要。 Android:該屬性只對網(wǎng)頁內(nèi)嵌視頻播放生效。 iOS:不支持。

參數(shù):

參數(shù)名參數(shù)類型必填默認值參數(shù)描述
accessbooleantrue設(shè)置有聲視頻播放是否需要用戶手動點擊。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()
    @State access: boolean = true
    build() {
      Column() {
        Web({ src: 'https://www.example.com', controller: this.controller })
          .mediaPlayGestureAccess(this.access)
      }
    }
  }

onHttpErrorReceive

onHttpErrorReceive(callback: (event?: { request: WebResourceRequest, response: WebResourceResponse }) => void)

網(wǎng)頁加載資源遇到的HTTP錯誤(響應(yīng)碼>=400)時觸發(fā)該回調(diào)。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
request[WebResourceRequest]網(wǎng)頁請求的封裝信息。
response[WebResourceResponse]資源響應(yīng)的封裝信息。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()

  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
        .onHttpErrorReceive((event) = > {
          if (event) {
            console.log('url:' + event.request.getRequestUrl())
            console.log('getResponseEncoding:' + event.response.getResponseEncoding())
            console.log('getResponseMimeType:' + event.response.getResponseMimeType())
            console.log('getResponseCode:' + event.response.getResponseCode())
            let result = event.request.getRequestHeader()
            console.log('The request header result size is ' + result.length)
            for (let i of result) {
              console.log('The request header key is : ' + i.headerKey + ' , value is : ' + i.headerValue)
            }
            let resph = event.response.getResponseHeader()
            console.log('The response header result size is ' + resph.length)
            for (let i of resph) {
              console.log('The response header key is : ' + i.headerKey + ' , value is : ' + i.headerValue)
            }
          }
        })
    }
  }
}

onProgressChange

onProgressChange(callback: (event?: { newProgress: number }) => void)

網(wǎng)頁加載進度變化時觸發(fā)該回調(diào)。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
newProgressnumber新的加載進度,取值范圍為0到100的整數(shù)。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()

  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
        .onProgressChange((event) = > {
          if (event) {
            console.log('newProgress:' + event.newProgress)
          }
        })
    }
  }
}

onScroll9+

onScroll(callback: (event: {xOffset: number, yOffset: number}) => void)

通知網(wǎng)頁滾動條滾動位置。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
xOffsetnumber以網(wǎng)頁最左端為基準,水平滾動條滾動所在位置。
yOffsetnumber以網(wǎng)頁最上端為基準,豎直滾動條滾動所在位置。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
      .onScroll((event) = > {
          console.info("x = " + event.xOffset)
          console.info("y = " + event.yOffset)
      })
    }
  }
}

onTitleReceive

onTitleReceive(callback: (event?: { title: string }) => void)

網(wǎng)頁document標題更改時觸發(fā)該回調(diào)。 Android和iOS的返回值與OpenHarmony不完全相同,以各平臺行為為準。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
titlestringdocument標題內(nèi)容。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()

  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
        .onTitleReceive((event) = > {
          if (event) {
            console.log('title:' + event.title)
          }
        })
    }
  }
}

onConsole

onConsole(callback: (event?: { message: ConsoleMessage }) => boolean)

通知宿主應(yīng)用JavaScript console消息。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
message[ConsoleMessage]觸發(fā)的控制臺信息。

返回值:

類型說明
boolean當返回true時,該條消息將不會再打印至控制臺,反之仍會打印至控制臺。iOS不支持。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()

    build() {
      Column() {
        Web({ src: 'https://www.example.com', controller: this.controller })
          .onConsole((event) = > {
            if (event) {
              console.log('getMessage:' + event.message.getMessage())
              console.log('getMessageLevel:' + event.message.getMessageLevel())
            }
            return false
          })
      }
    }
  }

onScaleChange9+

onScaleChange(callback: (event: {oldScale: number, newScale: number}) => void)

當前頁面顯示比例的變化時觸發(fā)該回調(diào)。 Android和iOS的頁面顯示比例與OpenHarmony不完全相同,以各平臺行為為準。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
oldScalenumber變化前的顯示比例百分比。
newScalenumber變化后的顯示比例百分比。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()

    build() {
      Column() {
        Web({ src: 'https://www.example.com', controller: this.controller })
          .onScaleChange((event) = > {
            console.log('onScaleChange changed from ' + event.oldScale + ' to ' + event.newScale)
          })
      }
    }
  }

onLoadIntercept10+

onLoadIntercept(callback: (event?: { data: WebResourceRequest }) => boolean)

當Web組件加載url之前觸發(fā)該回調(diào),用于判斷是否阻止此次訪問。默認允許加載。 在Android平臺,此接口在重定向時觸發(fā)。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
request[WebResourceRequest]url請求的相關(guān)信息。

返回值:

類型說明
boolean返回true表示阻止此次加載,否則允許此次加載。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()

    build() {
      Column() {
        Web({ src: 'https://www.example.com', controller: this.controller })
          .onLoadIntercept((event) = > {
            console.log('url:' + event.data.getRequestUrl())
            return true
          })
      }
    }
  }

onControllerAttached10+

onControllerAttached(callback: () => void)

當Controller成功綁定到Web組件時觸發(fā)該回調(diào),并且該Controller必須為WebviewController,因該回調(diào)調(diào)用時網(wǎng)頁還未加載,無法在回調(diào)中使用有關(guān)操作網(wǎng)頁的接口,可以使用[loadUrl]等操作網(wǎng)頁不相關(guān)的接口。

示例:

在該回調(diào)中使用loadUrl加載網(wǎng)頁

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()

    build() {
      Column() {
        Web({ src: '', controller: this.controller })
          .onControllerAttached(() = > {
            this.controller.loadUrl($rawfile("index.html"));
          })
      }
    }
  }

加載的html文件。

< !-- index.html -- >
  < !DOCTYPE html >
  < html >
      < body >
          < p >Hello World< /p >
      < /body >
  < /html >

onAlert

onAlert(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)

網(wǎng)頁觸發(fā)alert()告警彈窗時觸發(fā)回調(diào)。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
urlstring當前顯示彈窗所在網(wǎng)頁的URL。
messagestring彈窗中顯示的信息。
result[JsResult]通知Web組件用戶操作行為,iOS端時result.handleCancel行為和result.handleConfirm一致。

返回值:

類型說明
boolean當回調(diào)返回true時,應(yīng)用可以調(diào)用系統(tǒng)彈窗能力(包括確認和取消),并且需要根據(jù)用戶的確認或取消操作調(diào)用JsResult通知Web組件最終是否離開當前頁面。當回調(diào)返回false時,web組件暫不支持觸發(fā)默認彈窗。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()
    build() {
      Column() {
        Web({ src: $rawfile("index.html"), controller: this.controller })
          .onAlert((event) = > {
            if (event) {
              console.log("event.url:" + event.url)
              console.log("event.message:" + event.message)
              AlertDialog.show({
                title: 'onAlert',
                message: 'text',
                primaryButton: {
                  value: 'cancel',
                  action: () = > {
                    event.result.handleCancel()
                  }
                },
                secondaryButton: {
                  value: 'ok',
                  action: () = > {
                    event.result.handleConfirm()
                  }
                },
                cancel: () = > {
                  event.result.handleCancel()
                }
              })
            }
            return true
          })
      }
    }
  }

onConfirm

onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)

網(wǎng)頁調(diào)用confirm()告警時觸發(fā)此回調(diào)。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
urlstring當前顯示彈窗所在網(wǎng)頁的URL。
messagestring彈窗中顯示的信息。
result[JsResult]通知Web組件用戶操作行為。

返回值:

類型說明
boolean當回調(diào)返回true時,應(yīng)用可以調(diào)用系統(tǒng)彈窗能力(包括確認和取消),并且需要根據(jù)用戶的確認或取消操作調(diào)用JsResult通知Web組件。當回調(diào)返回false時,web組件暫不支持觸發(fā)默認彈窗,跨平臺目前這個返回值沒有作用。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()

    build() {
      Column() {
        Web({ src: $rawfile("index.html"), controller: this.controller })
          .onConfirm((event) = > {
            if (event) {
              console.log("event.url:" + event.url)
              console.log("event.message:" + event.message)
              AlertDialog.show({
                title: 'onConfirm',
                message: 'text',
                primaryButton: {
                  value: 'cancel',
                  action: () = > {
                    event.result.handleCancel()
                  }
                },
                secondaryButton: {
                  value: 'ok',
                  action: () = > {
                    event.result.handleConfirm()
                  }
                },
                cancel: () = > {
                  event.result.handleCancel()
                }
              })
            }
            return true
          })
      }
    }
  }

onPrompt9+

onPrompt(callback: (event?: { url: string; message: string; value: string; result: JsResult }) => boolean)

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
urlstring當前顯示彈窗所在網(wǎng)頁的URL。
messagestring彈窗中顯示的信息。
result[JsResult]通知Web組件用戶操作行為。

返回值:

類型說明
boolean當回調(diào)返回true時,應(yīng)用可以調(diào)用系統(tǒng)彈窗能力(包括確認和取消),并且需要根據(jù)用戶的確認或取消操作調(diào)用JsResult通知Web組件。當回調(diào)返回false時,web組件暫不支持觸發(fā)默認彈窗,跨平臺目前這個返回值沒有作用。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()

    build() {
      Column() {
        Web({ src: $rawfile("index.html"), controller: this.controller })
          .onPrompt((event) = > {
            if (event) {
              console.log("url:" + event.url)
              console.log("message:" + event.message)
              console.log("value:" + event.value)
              AlertDialog.show({
                title: 'onPrompt',
                message: 'text',
                primaryButton: {
                  value: 'cancel',
                  action: () = > {
                    event.result.handleCancel()
                  }
                },
                secondaryButton: {
                  value: 'ok',
                  action: () = > {
                    event.result.handlePromptConfirm(event.value)
                  }
                },
                cancel: () = > {
                  event.result.handleCancel()
                }
              })
            }
            return true
          })
      }
    }
  }

onHttpAuthRequest9+

onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, realm: string}) => boolean)

通知收到http auth認證請求。

Android加載頁面不會直接觸發(fā)該回調(diào),iOS加載頁面會直接觸發(fā)該回調(diào)。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
handler[HttpAuthHandler]通知Web組件用戶操作行為。
hoststringHTTP身份驗證憑據(jù)應(yīng)用的主機。
realmstringHTTP身份驗證憑據(jù)應(yīng)用的域。

返回值:

類型說明
boolean返回false表示此次認證失敗,否則成功,跨平臺目前這個返回值沒有作用。

示例:

// xxx.ets
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  httpAuth: boolean = false

  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
        .onHttpAuthRequest((event) = > {
          if (event) {
            AlertDialog.show({
              title: 'onHttpAuthRequest',
              message: 'text',
              primaryButton: {
                value: 'cancel',
                action: () = > {
                  event.handler.cancel()
                }
              },
              secondaryButton: {
                value: 'ok',
                action: () = > {
                  event.handler.confirm("2222", "2222");
                }
              },
              cancel: () = > {
                event.handler.cancel()
              }
            })
          }
          return true
        })
    }
  }
}

onGeolocationShow

onGeolocationShow(callback: (event?: { origin: string, geolocation: JsGeolocation }) => void)

通知用戶收到地理位置信息獲取請求。

目前iOS不支持。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
originstring指定源的字符串索引。
geolocation[JsGeolocation]通知Web組件用戶操作行為。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()
    build() {
      Column() {
        Web({ src:'https://www.example.com', controller:this.controller })
        .geolocationAccess(true)
        .onGeolocationShow((event) = > {
          if (event) {
            AlertDialog.show({
              title: 'title',
              message: 'text',
              confirm: {
                value: 'onConfirm',
                action: () = > {
                  event.geolocation.invoke(event.origin, true, true)
                }
              },
              cancel: () = > {
                event.geolocation.invoke(event.origin, false, true)
              }
            })
          }
        })
      }
    }
  }

onGeolocationHide

onGeolocationHide(callback: () => void)

通知用戶先前被調(diào)用[onGeolocationShow]時收到地理位置信息獲取請求已被取消。

目前iOS不支持。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
callback() => void地理位置信息獲取請求已被取消的回調(diào)函數(shù)。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()
    build() {
      Column() {
        Web({ src:'https://www.example.com', controller:this.controller })
        .geolocationAccess(true)
        .onGeolocationHide(() = > {
          console.log("onGeolocationHide...")
        })
      }
    }
  }

onPermissionRequest9+

onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void)

通知收到獲取權(quán)限請求。

iOS監(jiān)聽到webview權(quán)限申請的前提是要在plist設(shè)置app獲取權(quán)限選項,并且在首次打開應(yīng)用,系統(tǒng)彈出獲取權(quán)限窗口時選擇授予。

Android監(jiān)聽到webview權(quán)限申請的前提是要在Manifest中靜態(tài)配置。

getOrigin返回值以各平臺行為為準。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
request[PermissionRequest]通知Web組件用戶操作行為。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()
    build() {
      Column() {
        Web({ src: 'https://www.example.com', controller: this.controller })
          .onPermissionRequest((event) = > {
            if (event) {
              AlertDialog.show({
                title: 'title',
                message: 'text',
                primaryButton: {
                  value: 'deny',
                  action: () = > {
                    event.request.deny()
                  }
                },
                secondaryButton: {
                  value: 'onConfirm',
                  action: () = > {
                    event.request.grant(event.request.getAccessibleResource())
                  }
                },
                cancel: () = > {
                  event.request.deny()
                }
              })
            }
          })
      }
    }
  }

onPageVisible9+

onPageVisible(callback: (event: {url: string}) => void)

設(shè)置新頁面內(nèi)容即將可見時觸發(fā)的回調(diào)函數(shù)。

獲取的url以各平臺行為為準。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
urlstring新頁面內(nèi)容即將可見時新頁面的url地址。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'
  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()
    build() {
      Column() {
        Web({ src:'https://www.example.com', controller: this.controller })
         .onPageVisible((event) = > {
          console.log('onPageVisible url:' + event.url)
        })
      }
    }
  }

onDownloadStart

onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisposition: string, mimetype: string, contentLength: number }) => void)

通知主應(yīng)用開始下載一個文件

返回信息以各平臺行為為準,跨平臺目前只支持獲取url, userAgent, mimetype, contentLength。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
urlstring文件下載的URL。
userAgentstring用于下載的用戶代理。
mimetypestring服務(wù)器返回內(nèi)容媒體類型(MIME)信息。
contentLengthcontentLength服務(wù)器返回文件的長度。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview'

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()

    build() {
      Column() {
        Web({ src: 'https://www.example.com', controller: this.controller })
          .onDownloadStart((event) = > {
            if (event) {
              console.log('url:' + event.url)
              console.log('userAgent:' + event.userAgent)
              console.log('mimetype:' + event.mimetype)
              console.log('contentLength:' + event.contentLength)
            }
          })
      }
    }
  }

onShowFileSelector9+

onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector: FileSelectorParam }) => boolean)

調(diào)用此函數(shù)以處理具有“文件”輸入類型的HTML表單,以響應(yīng)用戶按下的“選擇文件”按鈕。

目前iOS不支持。

參數(shù):

參數(shù)名參數(shù)類型參數(shù)描述
result[FileSelectorResult]用于通知Web組件文件選擇的結(jié)果。
fileSelector[FileSelectorParam]文件選擇器的相關(guān)信息。

返回值:

類型說明
boolean當返回值為true時,用戶可以調(diào)用系統(tǒng)提供的彈窗能力。當回調(diào)返回false時,web組件暫不支持觸發(fā)默認彈窗。

示例:

// xxx.ets
  import web_webview from '@ohos.web.webview';
  import picker from '@ohos.file.picker';
  import { BusinessError } from '@ohos.base';

  @Entry
  @Component
  struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()
    @State uri: string = "file:///data/user/0/com.example.helloworld";

    build() {
      Column() {
        Web({ src: $rawfile('index.html'), controller: this.controller })
          .onShowFileSelector((event) = > {
            console.log('MyFileUploader onShowFileSelector invoked')
            event.result.handleFileList([this.uri]);
            return true
          })
      }
    }
  }

WebResourceError

web組件資源管理錯誤信息對象。

getErrorCode

getErrorCode(): number

獲取加載資源的錯誤碼。

錯誤碼:

Android和iOS的錯誤碼與OpenHarmony不完全相同,以各平臺錯誤碼為準。

返回值:

類型說明
number返回加載資源的錯誤碼。

getErrorInfo

getErrorInfo(): string

獲取加載資源的錯誤信息。
Android和iOS的錯誤信息與OpenHarmony不完全相同,以各平臺錯誤信息為準。

返回值:

類型說明
string返回加載資源的錯誤信息。

WebResourceRequest

web組件獲取資源請求對象。

getRequestUrl

getRequestUrl(): string

獲取資源請求的URL信息。

返回值:

類型說明
string返回資源請求的URL信息。

WebResourceResponse

web組件資源響應(yīng)對象。

getResponseMimeType

getResponseMimeType(): string

獲取資源響應(yīng)的媒體(MIME)類型。

返回值:

類型說明
string返回資源響應(yīng)的媒體(MIME)類型。

getResponseEncoding

getResponseEncoding(): string

獲取資源響應(yīng)的編碼。

返回值:

類型說明
string返回資源響應(yīng)的編碼。

getResponseCode

getResponseCode(): number

獲取資源響應(yīng)的狀態(tài)碼。

返回值:

類型說明
number返回資源響應(yīng)的狀態(tài)碼。

ConsoleMessage

Web組件獲取控制臺信息對象。

getMessage

getMessage(): string

獲取ConsoleMessage的日志信息。

返回值:

類型說明
string返回ConsoleMessage的日志信息。

getMessageLevel

getMessageLevel(): MessageLevel

獲取ConsoleMessage的信息級別。

返回值:

類型說明
[MessageLevel]返回ConsoleMessage的信息級別。

MessageLevel枚舉說明

名稱描述
Debug調(diào)試級別。
Error錯誤級別。
Info消息級別。
Log日志級別。
Warn警告級別。

JsResult

Web組件返回的彈窗確認或彈窗取消功能對象。

handleCancel

handleCancel(): void

通知Web組件用戶取消彈窗操作。

handleConfirm

handleConfirm(): void

通知Web組件用戶確認彈窗操作。

handlePromptConfirm9+

handlePromptConfirm(result: string): void

通知Web組件用戶確認彈窗操作及對話框內(nèi)容。

參數(shù):

參數(shù)名參數(shù)類型必填默認值參數(shù)描述
resultstring-用戶輸入的對話框內(nèi)容。

HttpAuthHandler9+

Web組件返回的http auth認證請求確認或取消和使用緩存密碼認證功能對象。

cancel9+

cancel(): void

通知Web組件用戶取消HTTP認證操作。

confirm9+

confirm(userName: string, pwd: string): boolean

使用用戶名和密碼進行HTTP認證操作。

參數(shù):

參數(shù)名參數(shù)類型必填默認值參數(shù)描述
userNamestring-HTTP認證用戶名。
pwdstring-HTTP認證密碼。

返回值:

類型說明
boolean認證成功返回true,失敗返回false??缙脚_Android和iOS底層不會有返回值,所以都返回true。

isHttpAuthInfoSaved9+

isHttpAuthInfoSaved(): boolean

通知Web組件用戶使用服務(wù)器緩存的帳號密碼認證。

返回值:

類型說明
boolean存在密碼認證成功返回true,其他返回false。iOS底層不會有返回值,所以暫時在獲取不到服務(wù)器緩存帳號密碼的時候返回false,如果能獲取到就進行認證并返回true。

JsGeolocation

Web組件返回授權(quán)或拒絕權(quán)限功能的對象。

invoke

invoke(origin: string, allow: boolean, retain: boolean): void

設(shè)置網(wǎng)頁地理位置權(quán)限狀態(tài)。

參數(shù):

參數(shù)名參數(shù)類型必填默認值參數(shù)描述
originstring-指定源的字符串索引。
allowboolean-設(shè)置的地理位置權(quán)限狀態(tài)。
retainboolean-是否允許將地理位置權(quán)限狀態(tài)保存到系統(tǒng)中。

PermissionRequest9+

Web組件返回授權(quán)或拒絕權(quán)限功能的對象。

deny9+

deny(): void

拒絕網(wǎng)頁所請求的權(quán)限。

getOrigin9+

getOrigin(): string

獲取網(wǎng)頁來源。

返回值:

類型說明
string當前請求權(quán)限網(wǎng)頁的來源。

getAccessibleResource9+

getAccessibleResource(): Array

獲取網(wǎng)頁所請求的權(quán)限資源列表,跨平臺資源列表支持的類型有RESOURCE_VIDEO_CAPTURE和RESOURCE_AUDIO_CAPTURE。

返回值:

類型說明
Array網(wǎng)頁所請求的權(quán)限資源列表。

grant9+

grant(resources: Array): void

對網(wǎng)頁訪問的給定權(quán)限進行授權(quán),跨平臺iOS不支持授予某一種類型的權(quán)限,只支持授予當前申請的權(quán)限,或拒絕當前申請的權(quán)限。

參數(shù):

參數(shù)名參數(shù)類型必填默認值參數(shù)描述
resourcesArray-授予網(wǎng)頁請求的權(quán)限的資源列表,跨平臺iOS此參數(shù)沒有作用。

FileSelectorResult9+

通知Web組件的文件選擇結(jié)果。

handleFileList9+

handleFileList(fileList: Array): void

通知Web組件進行文件選擇操作。

參數(shù):

參數(shù)名參數(shù)類型必填默認值參數(shù)描述
fileListArray-需要進行操作的文件列表。

FileSelectorParam9+

web組件獲取文件對象。

getTitle9+

getTitle(): string

獲取文件選擇器標題。

返回值:

類型說明
string返回文件選擇器標題。

getMode9+

getMode(): FileSelectorMode

獲取文件選擇器的模式。

返回值:

類型說明
[FileSelectorMode]返回文件選擇器的模式。

getAcceptType9+

getAcceptType(): Array

獲取文件過濾類型。

返回值:

類型說明
Array返回文件過濾類型。

isCapture9+

isCapture(): boolean

獲取是否調(diào)用多媒體能力。

返回值:

搜狗高速瀏覽器截圖20240326151450.png

類型說明HarmonyOS與OpenHarmony鴻蒙文檔籽料:mau123789是v直接拿
boolean返回是否調(diào)用多媒體能力。

FileSelectorMode枚舉說明

名稱描述
FileOpenMode打開上傳單個文件。
FileOpenMultipleMode打開上傳多個文件。
FileOpenFolderMode打開上傳文件夾模式。
FileSaveMode文件保存模式。

審核編輯 黃宇

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學習之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • 組件
    +關(guān)注

    關(guān)注

    1

    文章

    495

    瀏覽量

    17729
  • 鴻蒙
    +關(guān)注

    關(guān)注

    56

    文章

    2267

    瀏覽量

    42481
收藏 人收藏

    評論

    相關(guān)推薦

    鴻蒙ArkTS聲明組件:TextPicker

    滑動選擇文本內(nèi)容的組件
    的頭像 發(fā)表于 07-03 15:07 ?248次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>ArkTS</b><b class='flag-5'>聲明</b><b class='flag-5'>式</b><b class='flag-5'>組件</b>:TextPicker

    鴻蒙ArkTS聲明組件:TextInput

    單行文本輸入框組件。
    的頭像 發(fā)表于 07-03 09:14 ?461次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>ArkTS</b><b class='flag-5'>聲明</b><b class='flag-5'>式</b><b class='flag-5'>組件</b>:TextInput

    鴻蒙ArkTS聲明組件:StepperItem

    用作[Stepper]組件的頁面子組件
    的頭像 發(fā)表于 07-02 17:47 ?287次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>ArkTS</b><b class='flag-5'>聲明</b><b class='flag-5'>式</b><b class='flag-5'>組件</b>:StepperItem

    鴻蒙ArkTS聲明組件:TextArea

    多行文本輸入框組件,當輸入的文本內(nèi)容超過組件寬度時會自動換行顯示。
    的頭像 發(fā)表于 07-02 15:02 ?377次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>ArkTS</b><b class='flag-5'>聲明</b><b class='flag-5'>式</b><b class='flag-5'>組件</b>:TextArea

    鴻蒙ArkTS聲明組件:ScrollBar

    滾動條組件ScrollBar,用于配合可滾動組件使用,如List、Grid、Scroll。
    的頭像 發(fā)表于 07-01 15:52 ?334次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>ArkTS</b><b class='flag-5'>聲明</b><b class='flag-5'>式</b><b class='flag-5'>組件</b>:ScrollBar

    鴻蒙ArkTS聲明組件:Span

    作為Text組件的子組件,用于顯示行內(nèi)文本的組件
    的頭像 發(fā)表于 07-01 09:14 ?311次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>ArkTS</b><b class='flag-5'>聲明</b><b class='flag-5'>式</b><b class='flag-5'>組件</b>:Span

    鴻蒙ArkTS聲明組件:【RichText】

    富文本組件,解析并顯示HTML格式文本。
    的頭像 發(fā)表于 06-29 09:35 ?402次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>ArkTS</b><b class='flag-5'>聲明</b><b class='flag-5'>式</b><b class='flag-5'>組件</b>:【RichText】

    鴻蒙ArkTS聲明組件:NavDestination

    作為NavRouter組件的子組件,用于顯示導航內(nèi)容區(qū)。
    的頭像 發(fā)表于 06-27 14:05 ?289次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>ArkTS</b><b class='flag-5'>聲明</b><b class='flag-5'>式</b><b class='flag-5'>組件</b>:NavDestination

    鴻蒙ArkTS聲明組件:Marquee

    跑馬燈組件,用于滾動展示一段單行文本。僅當文本內(nèi)容寬度超過跑馬燈組件寬度時滾動,不超過時不滾動。
    的頭像 發(fā)表于 06-25 15:52 ?277次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>ArkTS</b><b class='flag-5'>聲明</b><b class='flag-5'>式</b><b class='flag-5'>組件</b>:Marquee

    鴻蒙ArkTS聲明組件:Blank

    空白填充組件,在容器主軸方向上,空白填充組件具有自動填充容器空余部分的能力。僅當父組件為Row/Column/Flex時生效。
    的頭像 發(fā)表于 06-19 16:21 ?395次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>ArkTS</b><b class='flag-5'>聲明</b><b class='flag-5'>式</b><b class='flag-5'>組件</b>:Blank

    HarmonyOS開發(fā)案例:【Web組件實現(xiàn)抽獎】

    基于ArkTS聲明開發(fā)范式的樣例,主要介紹了Web組件如何加載本地和云端H5小程序。
    的頭像 發(fā)表于 05-09 18:31 ?1203次閱讀
    HarmonyOS開發(fā)案例:【<b class='flag-5'>Web</b><b class='flag-5'>組件</b>實現(xiàn)抽獎】

    鴻蒙開發(fā)之ArkTS基礎(chǔ)知識

    一、ArkTS簡介 ArkTS是HarmonyOS優(yōu)選的主力應(yīng)用開發(fā)語言。它在TypeScript(簡稱TS)的基礎(chǔ)上,匹配了鴻蒙的ArkUI框架,擴展了聲明
    的頭像 發(fā)表于 01-24 16:44 ?1776次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)之<b class='flag-5'>ArkTS</b>基礎(chǔ)知識

    鴻蒙原生應(yīng)用/元服務(wù)實戰(zhàn)-Web隱私聲明

    這個位置的隱私申明是需要在WEB網(wǎng)頁下完成的,ArkTS鴻蒙原生應(yīng)用與元服務(wù)開發(fā)者,不一定熟悉這塊,一些公司也不一定有自己的服務(wù)器和域名、網(wǎng)站網(wǎng)頁或者相關(guān)權(quán)限是外包,沒法進行實時操作。所以,這塊要提前準備,要不會影響提交進度。
    發(fā)表于 01-24 15:05

    鴻蒙ArkTS的起源和簡介

    1、引言 Mozilla創(chuàng)造了JS,Microsoft創(chuàng)建了TS,Huawei進一步推出了ArkTS。 從最初的基礎(chǔ)的邏輯交互能力,到具備類型系統(tǒng)的高效工程開發(fā)能力,再到融合聲明UI、多維狀態(tài)管理
    發(fā)表于 01-16 16:23

    鴻蒙開發(fā)基礎(chǔ)-Web組件之cookie操作

    }) ... } ... 本文章主要是對鴻蒙開發(fā)當中ArkTS語言的基礎(chǔ)應(yīng)用實戰(zhàn),Web組件里的cookie操作。更多的鴻蒙應(yīng)用開發(fā)技
    發(fā)表于 01-14 21:31