本文正在參加星光計劃3.0–夏日挑戰賽
作者:陳日朗
前言
随着openharmony的快速發展,我們需要越來越多的應用來實作使用者的需求,在移動裝置的作業系統中,浏覽器則是必不可少的應用之一,接下來讓我們一起來實作一個簡單的浏覽器
實作原理
通過架構層提供的Web元件來實作對網頁的展示,通過webcontroller來控制網頁的簡單行為。
實作過程
1.網頁首頁
通路線上網頁時需添加網絡權限:ohos.permission.INTERNET
接口:
Web(options: { src: string, controller?: WebController })
首先,我們需要在代碼中使用Web接口建立一個網頁架構,這個接口接受兩個參數,第一個參數為路徑(線上網址路徑或者需要加載的本地檔案的路徑),第二個參數為一個webcontroller控制對象。代碼如下:
@Entry
@Component
struct Index {
build() {
Column() {
Web({ src: 'www.baidu.com', controller: new WebController() })
.width('100%')
.height('100%')
}
}
}
在有網絡的情況下,上述代碼将會打開一個百度首頁,并展示到我們應用的整個界面,一個簡單的浏覽器雛形已經出現。
2.網頁切換
接下來我們需要實作網頁之前的切換,我們需要在我們上面代碼的基礎上添加一個input框來作為網頁位址的輸入,并且監聽onChange和onSubmit事件來更新Web元件的src。代碼如下:
TextInput({
placeholder: '請在這裡輸入網址',
text: this.inputValue
})
.width('100%')
.height('56vp')
.onChange((value: string) => {
this.inputValue = value
})
.onSubmit(() => {
this.url = this.inputValue
this.wController.loadUrl({ url: this.url })
})
上述代碼我們在onChange事件中監聽到input的文本變化并更新目前的inputValue,在點選回車的時候将inputValue的值傳給web元件,并調用controller的loadUrl方法重新整理web頁面。
3.網頁前進/後退
接口:
webController: WebController = new WebController()
最後我們通過兩個簡單的按鈕來實作網頁的前進後退功能,我們需要用到上面提到了一個接口webController,通過這個接口我們可以對網頁做一些簡單的操作,包括但不限于前進,後退,重新整理,激活,清除曆史記錄等等,代碼如下:
private wController: WebController = new WebController()
...
Row() {
Button('前進').onClick(() => this.wController.forward())
Button('後退').onClick(() => this.wController.backward())
}
上述代碼我們調用的webController的forward和backward,分别可以對已經浏覽過的網頁進行前進和後退的切換。
總結
通過上面的三個步驟,我們已經實作了簡單的浏覽器功能,并且可以進行網頁切換和前進後退。其實浏覽器的主要功能都包含在Web元件中,我們隻需要調用webController的一些方法來實作浏覽器的基本功能。Web元件在OpenHarmony的開源api中算是使用比較簡單的,有興趣的小夥伴可以嘗試一下這個功能。
大家有什麼建議或者想法也可以在評論說出來一起探讨,最後我貼上本次案例的完整代碼,感謝大家觀看~
@Entry
@Component
struct Index {
@State inputValue: string = ''
@State url: string = 'www.baidu.com'
private wController: WebController = new WebController()
build() {
Column() {
TextInput({
placeholder: '請在這裡輸入網址',
text: this.inputValue
})
.width('100%')
.height('56vp')
.onChange((value: string) => {
this.inputValue = value
})
.onSubmit(() => {
this.url = this.inputValue
this.wController.loadUrl({ url: this.url })
})
Row() {
Button('前進').onClick(() => this.wController.forward())
Button('後退').onClick(() => this.wController.backward())
}
Web({ src: this.url, controller: this.wController })
.width('100%')
.height('100%')
}
}
}
更多原創内容請關注:深開鴻技術團隊
入門到精通、技巧到案例,系統化分享HarmonyOS開發技術,歡迎投稿和訂閱,讓我們一起攜手前行共建鴻蒙生态。