在Web页面中定义关闭弹窗的JavaScript函数,并在onBackPress中通过WebViewController.runJavaScript调用该函数,优先尝试关闭弹窗;若弹窗未打开或已关闭,则执行默认返回逻辑(如终止应用)。
import { webview } from '@kit.ArkWeb';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Index {
@State private webViewController: webview.WebviewController = new webview.WebviewController();
onBackPress() {
let url: string = this.webViewController.getUrl()
if (url === 'resource://rawfile/H5/index3.html') {
this.webViewController.runJavaScript('closeDialog()').then((result) => {
if (result === '"close dialog success"') {
console.info('关闭弹窗成功');
}else {
console.info('关闭网页成功');
// 若需要返回上一页,可使用this.webViewController.backward()
let context = getContext(this) as common.UIAbilityContext;
context.terminateSelf();
}
})
return true;
}
return false;
}
build() {
Column() {
Web({
src: $rawfile('H5/index3.html'),
controller: this.webViewController
})
.javaScriptAccess(true)
.width('80%')
.height('50%')
.backgroundColor('#CCF4F5')
.domStorageAccess(true)
}
.backgroundColor('#CCF4F5')
.justifyContent(FlexAlign.Center)
.width('100%').height('100%')
}
} <!DOCTYPE html>
<html style="font-size: 115.625px;">
<head>
<link rel="stylesheet" type="text/css" href="./css/index.css">
<meta charset="UTF-8">
<title>Web页面1</title>
</head>
<body>
<div id="dialog" style="width:800px;height:300px;border:1px solid black;display: flex;justify-content: center;align-items: center;"><p id="paragraph">这是一个弹窗</p></div>
<button style="width: 600px; height: 70px;font-size: 50px;" onclick="closeDialog()">点击关闭弹窗</button>
</body>
<script>
function closeDialog() {
var element = document.getElementById("dialog");
if(element.style.display != "none"){
element.style.display = "none";
return 'close dialog success'
}
}
</script>
</html>