背景

原本用uniApp开发的工程,原本场景为H5访问,工程中有外部链接跳转相关代码,在H5中,可以直接通过window.location.href方式跳转,但在微信小程序中此方案失效。

解决

微信小程序中,可通过新建页面,在页面中声明webview组件,在webview中加载外部链接的方式实现。

源码

在工程中新建web-view.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<template>
<web-view :src="data.webUrl"/>
</template>

<script setup lang="ts">
import { reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

const data = reactive({
webUrl: '',
});

onLoad((options) => {
console.log('进入webview');
console.log(options.url);
data.webUrl = decodeURIComponent(options.url);
});
</script>

在要跳转外部链接的地方,通过以下代码跳转到新建的web-view.vue页面,实现进入外部链接的效果:

1
2
3
uni.navigateTo({
url: `/pages/payment/web-view?url=${encodeURIComponent(finalUrl)}`,
});

特别注意:页面传参过程中,需对url进行encode/decode操作,否则诸如“-”、“=”、“+”等特殊符号可能会丢失。