ArkTS中定义一个js脚本读取当前页面的title信息,之后在ArkWeb组件的onPageEnd事件上,调用该脚本获取H5页面的title,并根据结果判断是否为登录页。如果为登录页,则当前窗口为隐私模式。import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
class windowUtils {
static setWindowPrivacyModeInPage(context: common.UIAbilityContext, isFlag: boolean) {
window.getLastWindow(context).then((lastWindow) => {
lastWindow.setWindowPrivacyMode(isFlag, (err: BusinessError) => {
const errCode: number = err.code;
if (errCode) {
console.error('Failed to set the window to privacy mode. 1Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in setting the window to privacy mode.');
});
});
}
}
@Entry
@Component
struct WebComponent {
// 读取网页标题
controller: webview.WebviewController = new webview.WebviewController();
jsCode: string = `function test(){
return document.title
}
test();`;
@State htmlTitle: string = '网页标题是:';
context = this.getUIContext();
build() {
Column() {
Text(this.htmlTitle)
// H5页面路径请替换为实际路径
// 根据网页标题判断如果为登录页,设置隐私模式
Web({ src: $rawfile("loginTest.html"), controller: this.controller }).fileAccess(false).geolocationAccess(false)
.onPageEnd((event) => {
if (event) {
this.controller.runJavaScript(this.jsCode)
.then((result) => {
this.htmlTitle = result.replaceAll('"', '');
if (this.htmlTitle === 'login') {
windowUtils.setWindowPrivacyModeInPage(this.context.getHostContext() as common.UIAbilityContext,
true);
} else {
windowUtils.setWindowPrivacyModeInPage(this.context.getHostContext() as common.UIAbilityContext,
false);
}
});
}
})
}
}
}