uni-app引入web-view组件后没有引用网页标题
uni-app引入web-view组件后没有引用网页标题
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | 10 | |
HBuilderX | 3.98 |
操作步骤:
- uniappX中引入web-view并且真机运行没有,不能自动获取webview中的title
预期结果:
- 可以根据网页变化动态显示title
实际结果:
- 不显示title
bug描述:
- uniappX中引入web-view并且真机运行没有,不能自动获取webview中的title
3 回复
uniapp可以动态改变标题,但是uniappx不可以
请收下,不用谢
uni-app-x webview组件不支持获取网页内容解决方案
在 uni-app
中使用 web-view
组件时,默认情况下不会自动显示网页的标题。web-view
组件只是嵌入了一个网页,但并不会自动处理网页的标题显示。如果你希望在 uni-app
中显示嵌入网页的标题,可以通过以下几种方式来实现:
方法一:手动设置页面标题
你可以在 web-view
加载完成后,通过 uni.setNavigationBarTitle
方法来手动设置页面标题。具体步骤如下:
- 在
web-view
组件上绑定@load
事件,监听网页加载完成。 - 在
@load
事件中,通过uni.setNavigationBarTitle
设置标题。
<template>
<view>
<web-view :src="url" @load="onWebViewLoad"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
url: 'https://example.com' // 替换为你要加载的网页地址
};
},
methods: {
onWebViewLoad(event) {
// 这里可以根据需要设置标题
uni.setNavigationBarTitle({
title: '自定义标题' // 替换为你想要的标题
});
}
}
};
</script>
方法二:通过网页的 title
动态设置标题
如果你希望动态获取网页的 title
并设置为 uni-app
的标题,可以通过 web-view
的 @message
事件与网页进行通信,获取网页的 title
。
- 在网页中通过 JavaScript 获取
document.title
,并通过postMessage
发送给uni-app
。 - 在
uni-app
中监听@message
事件,获取网页的title
并设置。
网页中的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>网页标题</title>
<script>
// 网页加载完成后,发送标题给 uni-app
window.onload = function() {
const title = document.title;
window.parent.postMessage({ title: title }, '*');
};
</script>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
uni-app 中的代码:
<template>
<view>
<web-view :src="url" @message="onWebViewMessage"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
url: 'https://example.com' // 替换为你要加载的网页地址
};
},
methods: {
onWebViewMessage(event) {
const title = event.detail.data[0].title;
uni.setNavigationBarTitle({
title: title
});
}
}
};
</script>
方法三:使用 uni-app
的 onNavigationBarChange
事件
如果你希望监听导航栏的变化,可以使用 uni-app
的 onNavigationBarChange
事件来动态设置标题。
<template>
<view>
<web-view :src="url"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
url: 'https://example.com' // 替换为你要加载的网页地址
};
},
onNavigationBarChange(e) {
// 这里可以根据需要设置标题
uni.setNavigationBarTitle({
title: '自定义标题' // 替换为你想要的标题
});
}
};
</script>