50.HarmonyOS鸿蒙系统 App(ArkUI)web组件实现简易浏览器
配置网络访问权限:
跳转任务:
Button('转到')
.onClick(() => {
try {
// 点击按钮时,通过loadUrl,跳转到www.example1.com
this.webviewController.loadUrl(this.get_url);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
前进代码:
Button('-->>').onClick(()=>{
if (this.webviewController.accessForward())
{
this.webviewController.forward();
return true;
}
})
后退代码:
Button('<<--').onClick(()=>{
if (this.webviewController.accessBackward())
{
this.webviewController.backward();
return true;
}
})
项目代码:
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
@State get_url:string = "www.cnblogs.com/"
@State cnblogs:string = 'www.cnblogs.com/'
@State csdn:string = 'txwtech.blog.csdn.net'
@State baidu:string = 'www.baidu.com'
controller: TextInputController = new TextInputController()
build() {
Column() {
Text('简易浏览器demo')
.backgroundColor(Color.Blue)
.fontColor(Color.White)
.fontSize(28)
Row()
{
Text('地址:')
TextInput({text: this.get_url, placeholder: '请输入网址...', controller: this.controller})
.onChange((value:string)=>{
this.get_url = value
})
.backgroundColor(Color.Gray)
}
Row()
{
Button("cnblogs").onClick(()=>{
this.get_url = this.cnblogs
})
Button('csdn').onClick(()=>{
this.get_url = this.csdn
})
Button('baidu').onClick(()=>{
this.get_url = this.baidu
})
}
Row()
{
Button('<<--').onClick(()=>{
if (this.webviewController.accessBackward())
{
this.webviewController.backward();
return true;
}
})
Button(' ')
Button(' ')
Button('转到')
.onClick(() => {
try {
// 点击按钮时,通过loadUrl,跳转到www.example1.com
this.webviewController.loadUrl(this.get_url);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Button(' ')
Button(' ')
Button('-->>').onClick(()=>{
if (this.webviewController.accessForward())
{
this.webviewController.forward();
return true;
}
})
}.borderColor(Color.Orange)
.backgroundColor(Color.Grey)
// 组件创建时,加载www.example.com
Web({ src: '', controller: this.webviewController})
}
}
}