uniapp内嵌webview域名拦截
新建webview的页面 web.vue 内容如下
<template>
<view class="view"></view>
</template>
<script>
export default {
name: 'web',
data() {
return {
url:'',
kWebview: null,
}
},
onLoad(option) {
var pages = getCurrentPages() // 获取栈实例
let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
let currentPage = pages[pages.length - 1]['$page']['fullPath'] //当前页面路径(带参数)
let url = currentPage.split('jumpUrl=')[1]
this.url = decodeURIComponent(url)
if (this.url) {
this.setupWebView()
} else {
uni.showToast({
title: '地址获取失败,请重新进入页面',
icon: 'none',
duration: 1500,
})
setTimeout(()=>{
uni.navigateBack()
}, 1500)
}
},
onBackPress(e) {
if (e.from === 'navigateBack') {
return false
}
// #ifdef APP-PLUS
var currentWebview = this.$scope.$getAppWebview();
currentWebview.children()[0].canBack(e => {
const canBack = e.canBack
if (canBack) {
this.kWebview.back();
} else {
uni.navigateBack();
}
})
// #endif
return true
},
onNavigationBarButtonTap(e) {
uni.navigateBack();
},
methods: {
setupWebView() {
let that = this
if(this.kWebview){return;}
// var w=plus.nativeUI.showWaiting()
this.kWebview = plus.webview.create("", "custom-webview", {
plusrequire: "none",
'uni-app': 'none',
top: uni.getSystemInfoSync().statusBarHeight + 44, // 适配底部高度
bottom: '0px',
})
that.kWebview.loadURL(that.url)
var currentWebview = that.$scope.$getAppWebview();
setTimeout(()=>{
currentWebview.append(that.kWebview)
const child = currentWebview.children()[0]
// match 正则,阻止匹配的地址,不传match 则全部阻止
let match = ''
// 拦截域名的正则 *表示该域名下的所有地址都包括
match = '(alipays://|https://xxx.xxxxx.xx).*'
// reject 表示拦截
that.kWebview.overrideUrlLoading({mode:"reject",match: match},(event)=>{
// 拦截成功的回调
let reg = RegExp(/APPLICATIONDETAILS/);
let content = event.url.split('?')[1]
let pages = getCurrentPages()
let prevPage = pages[pages.length - 2] //上一页
// 调用上一页方法 并返回上一页
if(event.url.match(reg)) {
prevPage.$vm.fun()
uni.navigateBack({
delta: 1
})
}
})
},200)
that.kWebview.onloaded({
})
}
}
}
</script>
<style lang="scss" scoped>
.view{
width: 100vw;
height: 100vh;
}
</style>
进入页面的代码如下
// 需要内嵌的页面地址
let url = encodeURIComponent('https://blog.csdn.net')
uni.navigateTo({
url: `/pages/web/web?jumpUrl=${url}`
})