背景
HarmonyOS平臺通過Web控件可支持網(wǎng)頁加載展示,Web在中是作為專項(xiàng)參考的。
本篇文章將從Android和iOS平臺研發(fā)角度出發(fā)來實(shí)踐學(xué)習(xí)API功能
說明
- 整個示例是以HarmonyOS開發(fā)文檔網(wǎng)址作為加載目標(biāo)
- 頁面布局增加了三個按鈕“后退”,“前進(jìn)”, “刷新”
效果
準(zhǔn)備
- 請參照
熟讀HarmonyOS Web組件指導(dǎo)
2.創(chuàng)建一個Demo工程,選擇Stage模型。
實(shí)踐總結(jié)
- UA可以設(shè)置,但無法通過API拿到自己設(shè)置的UA值
- 文件可以下載,但用戶沒有控制權(quán)
- 用戶無法控制定位權(quán)限申請
- Web控件當(dāng)前需要將UA設(shè)置為Android或者iOS特征的UA,大部分主流網(wǎng)站沒有適配鴻蒙Web
- 鴻蒙UA特征不明顯 Mozilla/5.0 (X11; Linux aarch64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.88 Mobile Safari/537.36
開始
頁面容器設(shè)置為沉浸式
import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
// 1.獲取應(yīng)用主窗口。
let windowClass: window.Window = null;
windowStage.getMainWindow((err, data) = > {
if (err.code) {
console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
return;
}
windowClass = data;
console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
// 2.實(shí)現(xiàn)沉浸式效果:設(shè)置導(dǎo)航欄、狀態(tài)欄顯示。
windowClass.setWindowSystemBarEnable(['status','navigation'], (err) = > {
if (err.code) {
console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in setting the system bar to be visible.');
});
})
//獲取當(dāng)前應(yīng)用內(nèi)最后顯示的窗口,使用callback異步回調(diào)
window.getLastWindow(this.context).then((result: window.Window) = > {
result.setWindowSystemBarEnable(['status', 'navigation'])
result.setWindowLayoutFullScreen(true);
})
windowStage.loadContent('pages/Index', (err, data) = > {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
});
}
}
創(chuàng)建WebView組件
文件路徑
根目錄/ets/entry/src/main/pages/WebView.ts
注冊頁面 main_pages.json
{
"src": [
"pages/Index"
,"pages/WebView"
]
}
功能實(shí)現(xiàn)
Cookie管理指導(dǎo)
網(wǎng)頁調(diào)試
功能介紹
- 支持多窗口
- 多窗口返回關(guān)閉
- 加載進(jìn)度提示
- 警告框,確認(rèn)框,提示框
- 權(quán)限申請
- 輸出調(diào)試日志
- 非http或https協(xié)議攔截
import web_webview from '@ohos.web.webview';
import router from '@ohos.router';
import common from '@ohos.app.ability.common';
import Url from '@ohos.url'
web_webview.once("webInited", () = > {
console.log("setCookie")
web_webview.WebCookieManager.setCookie("https://developer.harmonyos.com/", "author=harvey")
})
//在同一page頁有兩個web組件。在WebComponent新開窗口時,會跳轉(zhuǎn)到NewWebViewComp。
@CustomDialog
struct NewWebViewComp {
private controller?: CustomDialogController
private webviewController: web_webview.WebviewController = new web_webview.WebviewController()
build() {
Column() {
Web({ src: "", controller: this.webviewController })
.javaScriptAccess(true)
.multiWindowAccess(false)
.domStorageAccess(true)
.onWindowExit(() = > {
console.info("NewWebViewComp onWindowExit")
if (this.controller) {
this.controller.close()
}
})
}
}
}
@Entry
@Component
struct Index {
//www.useragentinfo.com
// @State webURL: string = 'https://m.bilibili.com/' //'https://developer.harmonyos.com/'
// @State webURL: string = 'https://www.baidu.com'
@State webURL: string = 'https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/start-overview-0000001478061421-V3?catalogVersion=V3'
@State back: boolean = true
@State forward: boolean = false
@State showProgress: boolean = false
@State currentProgress: number = 0
@State buttonColorFocusColor: number = Color.Black
@State buttonColorDisableColor: number = Color.Gray
@State currentButtonColor: number = this.buttonColorFocusColor
private webviewController: web_webview.WebviewController = new web_webview.WebviewController();
private context = getContext(this) as common.UIAbilityContext;
dialogController: CustomDialogController | null = null
aboutToAppear() {
web_webview.WebviewController.setWebDebuggingAccess(true)
let params = router.getParams()
if (params) {
this.webURL = params['targetUrl'];
}
}
build() {
Column() {
Stack() {
Web({ src: this.webURL, controller: this.webviewController })
.width('100%')
.height('100%')
.userAgent('Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36 HarveyHarmonyOS/1.0.0')
.multiWindowAccess(true)
.javaScriptAccess(true)
.geolocationAccess(true)
.imageAccess(true)
.onlineImageAccess(true)
.domStorageAccess(true)
.fileAccess(true)
.mediaPlayGestureAccess(true)
.mixedMode(MixedMode.Compatible)
.onTitleReceive((info) = > {
console.log('標(biāo)題欄: ' + info.title)
})
.onProgressChange((progress) = > {
console.log('當(dāng)前加載進(jìn)度 ' + progress.newProgress)
this.currentProgress = progress.newProgress
if (progress.newProgress >= 0 && progress.newProgress < 100) {
this.showProgress = true
} else if (progress.newProgress == 100) {
this.showProgress = false
}
if (this.webviewController.accessForward()) {
this.forward = true
this.currentButtonColor = this.buttonColorFocusColor
} else {
this.forward = false
this.currentButtonColor = this.buttonColorDisableColor
}
console.log('userAgent: ' + this.webviewController.getUserAgent())
})
.onErrorReceive((error) = > {
console.log(error.request.getRequestUrl())
console.log(JSON.stringify(error.error))
})
.onHttpErrorReceive((error) = > {
console.log(JSON.stringify(error.response))
})
.onSslErrorEventReceive((info) = > {
})
.onRenderExited(() = > {
console.log('onRenderExited')
})
.onUrlLoadIntercept((info) = > {
if(!info.data.toString().toLowerCase().startsWith("https://") || !info.data.toString().toLowerCase().startsWith("https://")){
console.log('攔截信息: ' + JSON.stringify(info))
return true;
}
console.log('信息: ' + JSON.stringify(info))
//false : 不攔截 true: 攔截
return false
})
.onDownloadStart( (event) = > {
AlertDialog.show({
title: event.url,
message: event.url,
primaryButton: {
value: 'cancel',
action: () = > {
}
}
})
})
.onAlert((event) = > {
AlertDialog.show({
title: event.url,
message: event.message,
confirm: {
value: 'onAlert',
action: () = > {
event.result.handleConfirm()
}
},
cancel: () = > {
event.result.handleCancel()
}
})
return true
})
.onConfirm((event) = > {
AlertDialog.show({
title: event.url,
message: event.message,
confirm: {
value: 'onConfirm',
action: () = > {
event.result.handleConfirm()
}
},
cancel: () = > {
event.result.handleCancel()
}
})
return true;
})
.onPrompt((event) = > {
AlertDialog.show({
title: event.url,
message: event.message,
primaryButton: {
value: 'cancel',
action: () = > {
event.result.handleCancel()
}
},
secondaryButton: {
value: 'ok',
action: () = > {
event.result.handleConfirm()
}
},
cancel: () = > {
event.result.handleCancel()
}
})
return true;
})
.onConsole((msg) = > {
console.error('網(wǎng)頁日志:' + JSON.stringify(msg.message.getMessage()))
return true
})
.onWindowNew((event) = > {
console.log('新開window')
if (!event.isAlert) {
router.pushUrl({ url: 'custompages/WebView', params: {
"targetUrl": event.targetUrl
} })
.then(() = > {
console.info('Succeeded in jumping to the second page.')
}).catch((error) = > {
console.log(error)
})
} else {
if (this.dialogController) {
this.dialogController.close()
}
let popController: web_webview.WebviewController = new web_webview.WebviewController()
this.dialogController = new CustomDialogController({
builder: NewWebViewComp({ webviewController: popController })
})
this.dialogController.open()
//將新窗口對應(yīng)WebviewController返回給Web內(nèi)核。
//如果不需要打開新窗口請調(diào)用event.handler.setWebController接口設(shè)置成null。
//若不調(diào)用event.handler.setWebController接口,會造成render進(jìn)程阻塞。
event.handler.setWebController(popController)
}
})
.onWindowExit(() = > {
console.log('已推出window')
})
.onGeolocationHide(() = > {
console.log('geo隱藏')
})
.onGeolocationShow((info) = > {
info.geolocation.invoke(info.origin, false, false)
console.log(info.origin + ' 有定位需求')
})
.onPageBegin((info) = > {
console.error(info.url)
let host = Url.URL.parseURL(info.url).host
try {
let cookie = web_webview.WebCookieManager.getCookie(host)
console.log('Bcookie: ' + cookie)
} catch (e) {
console.error(e)
}
})
.onPageEnd((info) = > {
let host = Url.URL.parseURL(info.url).host
try {
let cookie = web_webview.WebCookieManager.getCookie(host)
console.log('Bcookie: ' + cookie)
} catch (e) {
console.error(e + ' ' + info.url)
}
})
.onBeforeUnload((info) = > {
return false
})
.onRefreshAccessedHistory((info) = > {
})
.onResourceLoad(() = > {
})
.onFullScreenEnter((info) = > {
})
.onFullScreenExit(() = > {
})
.onPermissionRequest((event) = > {
AlertDialog.show({
title: 'title',
message: event.request.getAccessibleResource()[0],
primaryButton: {
value: 'deny',
action: () = > {
event.request.deny()
}
},
secondaryButton: {
value: 'onConfirm',
action: () = > {
event.request.grant(event.request.getAccessibleResource())
}
},
cancel: () = > {
event.request.deny()
}
})
})
.onInterceptKeyEvent((info) = > {
console.log(info.keyCode + ' ' + info.keyText)
return false
})
.onPageVisible((info) = > {
console.log(info.url)
})
if (this.showProgress) {
Progress({ value: this.currentProgress, total: 100, type: ProgressType.Linear })
.width('100%').height(45)
}
}.height('93%').alignContent(Alignment.TopStart)
Row() {
Text('后退')
.fontSize(18)
.enabled(this.back)
.onClick(() = > {
if (this.webviewController.accessBackward()) {
this.webviewController.backward()
} else {
if ("1" === router.getLength()) {
this.context.terminateSelf()
} else {
router.back()
}
}
})
.width('30%')
.height('100%')
.textAlign(TextAlign.Center)
Text('前進(jìn)')
.fontSize(18)
.fontColor(this.currentButtonColor)
.onClick(() = > {
if (this.webviewController.accessForward()) {
this.webviewController.forward()
}
})
.width('30%')
.height('100%')
.textAlign(TextAlign.Center)
Text('刷新')
.fontSize(18)
.fontColor(Color.Black)
.onClick(() = > {
this.webviewController.refresh()
})
.width('30%')
.height('100%')
.textAlign(TextAlign.Center)
}.width('100%').height('5%')
.backgroundColor(Color.White)
.justifyContent(FlexAlign.SpaceBetween)
}.width('100%').height('100%')
.padding({ top: px2vp(111) })
}
}
審核編輯 黃宇
聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點(diǎn)僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。
舉報投訴
-
Web
+關(guān)注
關(guān)注
2文章
1286瀏覽量
71260 -
鴻蒙
+關(guān)注
關(guān)注
59文章
2594瀏覽量
43965 -
HarmonyOS
+關(guān)注
關(guān)注
80文章
2117瀏覽量
32761 -
鴻蒙OS
+關(guān)注
關(guān)注
0文章
191瀏覽量
4965
發(fā)布評論請先 登錄
相關(guān)推薦
熱點(diǎn)推薦
鴻蒙開發(fā)基礎(chǔ)-Web組件之cookie操作
})
...
}
...
本文章主要是對鴻蒙開發(fā)當(dāng)中ArkTS語言的基礎(chǔ)應(yīng)用實(shí)戰(zhàn),Web組件里的cookie操作。更多的鴻蒙應(yīng)用開發(fā)技
發(fā)表于 01-14 21:31
鴻蒙原生應(yīng)用/元服務(wù)實(shí)戰(zhàn)-Web隱私聲明
這個位置的隱私申明是需要在WEB網(wǎng)頁下完成的,ArkTS鴻蒙原生應(yīng)用與元服務(wù)開發(fā)者,不一定熟悉這塊,一些公司也不一定有自己的服務(wù)器和域名、網(wǎng)站網(wǎng)頁
發(fā)表于 01-24 15:05
鴻蒙OS應(yīng)用程序開發(fā)
這份學(xué)習(xí)文檔主要是帶領(lǐng)大家在鴻蒙OS上學(xué)習(xí)開發(fā)一個應(yīng)用程序,主要知識點(diǎn)如下:1、U-Boot引導(dǎo)文件燒寫方式;2、內(nèi)核鏡像燒寫方式;3、鏡像運(yùn)行。
發(fā)表于 09-11 14:39
Nodemcu web網(wǎng)頁顯示簡介
Nodemcu-0.96oled-dht11-web網(wǎng)頁顯示簡介1.軟件部分Arduino IDE2.硬件部分NodeMCUOLEDDHT113.知識點(diǎn)Web開發(fā)Arduino IDE
發(fā)表于 11-01 07:34
鴻蒙 OS 應(yīng)用開發(fā)初體驗(yàn)
的操作系統(tǒng)平臺和開發(fā)框架。HarmonyOS 的目標(biāo)是實(shí)現(xiàn)跨設(shè)備的無縫協(xié)同和高性能。
DevEco Studio
對標(biāo) Android Studio,開發(fā)鴻蒙 OS 應(yīng)用的 IDE。
發(fā)表于 11-02 19:38
嵌入式系統(tǒng)設(shè)計(jì)與實(shí)例開發(fā)—ARM與uC/OS-Ⅱ
嵌入式系統(tǒng)設(shè)計(jì)與實(shí)例開發(fā) ——ARM與uC/OS-Ⅱ
發(fā)表于 11-08 17:32
?0次下載
華為鴻蒙OS 2.0帶來哪些智慧體驗(yàn)?
華為已經(jīng)定于12月16日在北京發(fā)布鴻蒙OS 2.0手機(jī)開發(fā)者Beta版本。這不僅是手機(jī)鴻蒙OS的首次亮相,同時也意味著手機(jī)
鴻蒙OS 2.0手機(jī)開發(fā)者Beta版發(fā)布會在京舉辦
三個月前,鴻蒙OS 2.0正式在華為開發(fā)者大會2020亮相。12月16日,鴻蒙OS 2.0手機(jī)開發(fā)
華為正式推出鴻蒙OS的手機(jī)開發(fā)者Beta版
12月16日上午消息,華為今日宣布正式推出鴻蒙OS的手機(jī)開發(fā)者Beta版,華為消費(fèi)者業(yè)務(wù)軟件部總裁王成錄表示,今年已有美的、九陽、老板電器、海雀科技搭載鴻蒙
華為發(fā)布鴻蒙OS Beta版
昨天華為發(fā)布鴻蒙OS Beta版了?鴻蒙系統(tǒng)一直在按照既有步伐前進(jìn),現(xiàn)在華為發(fā)布鴻蒙OS Beta版,而且一些生態(tài)
鴻蒙OS與Lite OS的區(qū)別是什么
鴻蒙OS鴻蒙OS面向未來、面向全場景、分布式。在單設(shè)備系統(tǒng)能力基礎(chǔ)上,鴻蒙OS提出了基于同一套系
鴻蒙os怎么升級
6月2日,華為正式發(fā)布了鴻蒙armonyOS 2系統(tǒng),那么鴻蒙os如何升級?現(xiàn)將鴻蒙os升級方式告知如下。
華為開發(fā)者大會2021鴻蒙os在哪場
華為開發(fā)者大會2021將在10月22日-24日舉辦,地點(diǎn)為東莞松山湖,鴻蒙os 3.0或?qū)⑴c我們見面,那么華為開發(fā)者大會2021鴻蒙
通過Web網(wǎng)頁控制開發(fā)板LED燈
接下來將介紹如何通過Web網(wǎng)頁來控制開發(fā)板上的LED燈,本文只是在網(wǎng)頁上實(shí)現(xiàn)功能,并無交互功能,與開發(fā)板的交互功能實(shí)現(xiàn)將在《

web前端開發(fā)和前端開發(fā)的區(qū)別
、CSS和JavaScript等技術(shù)來構(gòu)建用戶界面,實(shí)現(xiàn)用戶與應(yīng)用程序的交互。Web前端開發(fā)包括網(wǎng)頁設(shè)計(jì)、網(wǎng)頁編碼、前端框架使用以及優(yōu)化頁面性能等任務(wù)。 前端
評論