【UniApp跳转外部链接】实现方案
🌻🌻前言
在跨平台开发中,外部链接跳转是常见需求。本文将针对UniApp框架,详细讲解不同场景下实现外部链接跳转的解决方案,并提供最佳实践建议。
方案实现:
UniApp实现外部链接跳转需要针对不同平台采用不同方案:
H5:直接使用window.open或webview
微信小程序:必须使用web-view组件
App:推荐使用plus.runtime.openURL
H5平台实现方式
// 方式1:使用内置API
uni.navigateTo({
url: '/pages/webview/webview?url=' + encodeURIComponent('https://www.example.com')
})
// 方式2:直接页面跳转(新窗口)
window.open('https://www.example.com', '_blank')
配套webview页面:
<template>
<web-view :src="url"></web-view>
</template>
<script>
export default {
data() {
return {
url: ''
}
},
onLoad(options) {
this.url = decodeURIComponent(options.url)
}
}
</script>
微信小程序方案
// 使用web-view组件前需配置业务域名
uni.navigateTo({
url: '/pages/webview/webview?url=' + encodeURIComponent('https://www.example.com')
})
注意事项:
- 需登录微信公众平台配置业务域名
- 域名必须备案且支持HTTPS
- 每个小程序最多配置200个业务域名
App端实现方式
// 使用系统浏览器打开
plus.runtime.openURL('https://www.example.com', (err) => {
if(err) {
uni.showToast({ title: '打开链接失败', icon: 'none' })
}
})
// 或使用内置Webview
uni.navigateTo({
url: '/pages/webview/webview?url=' + encodeURIComponent('https://www.example.com')
})