背景
HarmonyOS平臺(tái)通過Web控件可支持網(wǎng)頁(yè)加載展示,Web在中是作為專項(xiàng)參考的。
本篇文章將從Android和iOS平臺(tái)研發(fā)角度出發(fā)來(lái)實(shí)踐學(xué)習(xí)API功能
說(shuō)明
- 整個(gè)示例是以HarmonyOS開發(fā)文檔網(wǎng)址作為加載目標(biāo)
- 頁(yè)面布局增加了三個(gè)按鈕“后退”,“前進(jìn)”, “刷新”
效果
準(zhǔn)備
- 請(qǐng)參照
熟讀HarmonyOS Web組件指導(dǎo)
2.創(chuàng)建一個(gè)Demo工程,選擇Stage模型。
實(shí)踐總結(jié)
- UA可以設(shè)置,但無(wú)法通過API拿到自己設(shè)置的UA值
- 文件可以下載,但用戶沒有控制權(quán)
- 用戶無(wú)法控制定位權(quán)限申請(qǐng)
- 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
開始
頁(yè)面容器設(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
注冊(cè)頁(yè)面 main_pages.json
{
"src": [
"pages/Index"
,"pages/WebView"
]
}
功能實(shí)現(xiàn)
Cookie管理指導(dǎo)
網(wǎng)頁(yè)調(diào)試
功能介紹
- 支持多窗口
- 多窗口返回關(guān)閉
- 加載進(jìn)度提示
- 警告框,確認(rèn)框,提示框
- 權(quán)限申請(qǐng)
- 輸出調(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頁(yè)有兩個(gè)web組件。在WebComponent新開窗口時(shí),會(huì)跳轉(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)頁(yè)日志:' + 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()
//將新窗口對(duì)應(yīng)WebviewController返回給Web內(nèi)核。
//如果不需要打開新窗口請(qǐng)調(diào)用event.handler.setWebController接口設(shè)置成null。
//若不調(diào)用event.handler.setWebController接口,會(huì)造成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) })
}
}
審核編輯 黃宇
-
Web
+關(guān)注
關(guān)注
2文章
1287瀏覽量
71450 -
鴻蒙
+關(guān)注
關(guān)注
60文章
2620瀏覽量
44063 -
HarmonyOS
+關(guān)注
關(guān)注
80文章
2126瀏覽量
33092 -
鴻蒙OS
+關(guān)注
關(guān)注
0文章
191瀏覽量
4997
發(fā)布評(píng)論請(qǐng)先 登錄
鴻蒙開發(fā)基礎(chǔ)-Web組件之cookie操作
鴻蒙原生應(yīng)用/元服務(wù)實(shí)戰(zhàn)-Web隱私聲明
鴻蒙OS應(yīng)用程序開發(fā)
Nodemcu web網(wǎng)頁(yè)顯示簡(jiǎn)介
鴻蒙 OS 應(yīng)用開發(fā)初體驗(yàn)
嵌入式系統(tǒng)設(shè)計(jì)與實(shí)例開發(fā)—ARM與uC/OS-Ⅱ
華為鴻蒙OS 2.0帶來(lái)哪些智慧體驗(yàn)?
鴻蒙OS 2.0手機(jī)開發(fā)者Beta版發(fā)布會(huì)在京舉辦
華為正式推出鴻蒙OS的手機(jī)開發(fā)者Beta版
華為發(fā)布鴻蒙OS Beta版
鴻蒙OS與Lite OS的區(qū)別是什么
鴻蒙os怎么升級(jí)
華為開發(fā)者大會(huì)2021鴻蒙os在哪場(chǎng)
通過Web網(wǎng)頁(yè)控制開發(fā)板LED燈

評(píng)論