onTitleReceive的callback回调参数OnTitleReceiveEvent中的isRealTitle表示document标题来源,true表示来自网页的title标签,false表示该title是根据URL自动生成,默认返回为false。
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.fileAccess(false)
.geolocationAccess(false)
.domStorageAccess(true)
.onTitleReceive((event) => {
if (event) {
console.info(`title:${event.title}, is from title: ${event?.isRealTitle}`);
} else {
console.error('onTitleReceive callback error');
}
});
};
}
} import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct Index {
wController: webview.WebviewController = new webview.WebviewController();
@State url: string = 'xxx'; // 实际场景请替换为可访问地址
build() {
Column() {
Column() {
Web({ src: this.url, controller: this.wController })
.geolocationAccess(false)
.fileAccess(true)
.javaScriptAccess(true)
.domStorageAccess(true) // 设置是否开启文档对象模型存储接口(DOM Storage API)权限,默认未开启。
.overviewModeAccess(true)
.verticalScrollBarAccess(false)
.onTitleReceive((event) => {
if (event) {
// 方式一:在onTitleReceive回调中获取标题,只有当网页标题发生变化时触发
console.info(`onTitleReceive title: ${event.title}`);
}
})
.onPageEnd(() => {
// 方式二:在onPageEnd回调中使用getTitle获取标题
console.info('onPageEnd title:', this.wController.getTitle());
// 方式三:通过runJavaScript执行JavaScript脚本获取标题
// 异步执行JavaScript脚本,并通过回调方式返回脚本执行的结果
this.wController.runJavaScript('document.title', (error, result) => {
if (error) {
console.error(`Failed to get title. Code is ${error.code}, message is ${error.message}`);
} else {
console.info('Page title:', result);
}
});
});
}
.width('100%')
.height('100%');
};
}
}