Web组件用于在应用程序中显示Web页面内容,为开发者提供页面加载、页面交互、页面调试等能力
-
页面加载:Web组件提供基础的前端页面加载的能力,包括加载网络页面、本地页面、Html格式文本数据。
-
页面交互:Web组件提供丰富的页面交互的方式,包括:设置前端页面深色模式,新窗口中加载页面,位置权限管理,Cookie管理,应用侧使用前端页面JavaScript等能力。
-
页面调试:Web组件支持使用Devtools工具调试前端页面。
-
Web组件需要 src和controller两个属性:
-
src: 可以是网络地址 、HTML格式的富文本数据、也可以是来自鸿蒙本身的沙箱或者资源原生地址
controller: 用来管控Web组件的一些行为 包括后续的通信。
1.1利用 Web 组件 + RichText 组件实现隐私政策界面前端 html 文件的展示?
利用webView加载rawfile中的html文件: -> 混合式开发(前端网页 + 端开发)
webViewController:webview.WebviewController = new webview.WebviewController()
Web({
src:$rawfile('index.html'),
//$rawfile()方法来读取html文件的路径
controller:this.webViewController
})
//调用loadUrl()接口变更网页
this.webviewController.loadUrl('www.example1.com');
注意:Web第二个参数controller不能省略,必选
src: 可以指向本地的一个文件,也可以指向网络的一个html文件,如果是网络文件,则需要在src/main/module.json5 配置INTERNET网络访问权限
预览器不支持加载网页功能,需要到模拟器或者真机中验证功能结果
1.2 利用 RichText 实现富文本的展示?
- 利用html结构实现富文本在真机next系统上的兼容处理。
-
在next版本中直接把富文本字符串交给RichText显示时,在真机和模拟器上文字显示会特别的小,需要把需要显示的富文本字符串使用一段html结构,并且使用一个
<div style="font-44size:34px"></div>
来包裹这段富文本字符串才能显示正常。
Column() {
Scroll() {
// 富文本
// RichText(this.question.answer)
RichText(`
<html>
<body>
<div style="font-size:54px">${this.question.answer}</div>
<body>
</html>
`)
}
.padding((15))
.layoutWeight(1)
.onScroll((xOffset: number, yOffset: number) => {
console.log('mylog->xOffset', xOffset + ' ' + yOffset)
})
.onScrollStop(() => {
console.log('mylog->Scroll Stop')
})
}.layoutWeight(1)
1.3 WebView单词用法高亮显示?
如何在鸿蒙原生应用中加载html 以及如何执行html中的一个js方法?
- 利用WebView加载html文件,当html文件加载完成后会触发onPageEnd方法
- 在onPageEnd方法中利用WebViewController对象中的runJavaScript方法 来调用html中的 定义的js方法 writeWord
webviewCtrl: webview.WebviewController = new webview.WebviewController()
Web({
src: $rawfile('word.html'),
controller: this.webviewCtrl
})
.onPageEnd(() => {
// 当word.html网页加载完成之后,要执行这个网页中定义的js方法 writeWord
this.webviewCtrl.runJavaScript(`writeWord(\`${this.currentCode}\`)`)
})
h5:
<style>
word {
font-size: 16px;
line-height: 1.6
}
</style>
</head>
<body>
<h1>heiio</h1>
<pre><code></code></pre>
<script>
function writeWord(str) {
const el = document.querySelector('word');
el.innerHTML = hljs.highlightAuto(str).value;
}
</script>
参考: