<template>
|
<view class="container">
|
<web-view v-if="webViewUrl" class="webview-content" :src="webViewUrl"></web-view>
|
<view v-else class="empty-box">
|
<text class="empty-text">链接地址无效</text>
|
</view>
|
</view>
|
</template>
|
|
<script setup lang="ts">
|
import { ref } from 'vue'
|
import { onLoad, onUnload } from '@dcloudio/uni-app'
|
|
const webViewUrl = ref('')
|
let currentWebviewInstance: any = null
|
|
/**
|
* 页面加载时读取外链地址与标题。
|
*/
|
onLoad((options) => {
|
const resolvedUrl = decodeQueryValue(options?.url)
|
const resolvedTitle = decodeQueryValue(options?.title)
|
webViewUrl.value = resolvedUrl
|
if (resolvedTitle) {
|
uni.setNavigationBarTitle({
|
title: resolvedTitle,
|
})
|
}
|
|
// #ifdef APP-PLUS
|
// 获取当前 WebView 实例
|
setTimeout(() => {
|
currentWebviewInstance = plus.webview.currentWebview()
|
console.log('[WebView] 页面加载完成,URL:', resolvedUrl)
|
}, 100)
|
// #endif
|
})
|
|
/**
|
* 页面卸载时清除 WebView 缓存和 Cookie
|
*/
|
onUnload(() => {
|
console.log('[WebView] 页面卸载,开始清除缓存')
|
clearWebViewData()
|
})
|
|
/**
|
* 清除 WebView 的缓存、Cookie 和存储数据
|
*/
|
function clearWebViewData() {
|
try {
|
// #ifdef APP-PLUS
|
if (currentWebviewInstance) {
|
// 清除 WebView 缓存
|
if (typeof currentWebviewInstance.clearCache === 'function') {
|
currentWebviewInstance.clearCache()
|
console.log('[WebView] 缓存已清除')
|
}
|
|
// 清除 Cookie
|
if (typeof currentWebviewInstance.evalJS === 'function') {
|
// 通过 JS 清除 Cookie
|
currentWebviewInstance.evalJS(`
|
document.cookie.split(";").forEach(function(c) {
|
document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
|
});
|
// 清除 localStorage 和 sessionStorage
|
if (window.localStorage) localStorage.clear();
|
if (window.sessionStorage) sessionStorage.clear();
|
console.log('[WebView.evalJS] Cookie 和存储已清除');
|
`)
|
console.log('[WebView] Cookie 和存储已清除')
|
}
|
}
|
|
// 清除所有 WebView 的缓存
|
const allWebviews = plus.webview.all()
|
if (allWebviews && allWebviews.length > 0) {
|
allWebviews.forEach((webview) => {
|
if (webview && typeof webview.clearCache === 'function') {
|
webview.clearCache()
|
}
|
})
|
console.log('[WebView] 所有 WebView 缓存已清除')
|
}
|
// #endif
|
} catch (error) {
|
console.error('[WebView] 清除数据失败:', error)
|
}
|
}
|
|
/**
|
* 解码路由参数,异常时回退为空字符串。
|
*/
|
function decodeQueryValue(value: unknown) {
|
if (typeof value !== 'string' || !value.trim()) {
|
return ''
|
}
|
try {
|
return decodeURIComponent(value)
|
} catch {
|
return value.trim()
|
}
|
}
|
</script>
|
|
<style lang="scss" scoped>
|
.container {
|
width: 100vw;
|
min-height: 100vh;
|
background-color: #ffffff;
|
}
|
|
.webview-content {
|
width: 100%;
|
height: 100vh;
|
}
|
|
.empty-box {
|
min-height: 100vh;
|
display: flex;
|
align-items: center;
|
justify-content: center;
|
}
|
|
.empty-text {
|
font-size: 28rpx;
|
color: #999999;
|
}
|
</style>
|