參見:
https://www.jianshu.com/p/5bc4589dd034
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html
2020年7月微信開放了H5跳轉小程序的實現(基於微信JSDK和開放標簽)。微信官方文檔 僅有 js 示例,工作中用的是vue,特此記錄備忘。
微信開放標簽是微信公眾平台面向網頁開發者提供的擴展標簽集合。通過使用微信開放標簽,網頁開發者可安全便捷地使用微信或系統的能力,為微信用戶提供更優質的網頁體驗。
此文檔面向網頁開發者,介紹微信開放標簽如何使用及相關注意事項。需要注意的是,微信開放標簽有最低的微信版本要求,以及最低的系統版本要求。
微信版本要求為:7.0.12及以上。 系統版本要求為:iOS 10.3及以上、Android 5.0及以上。
代碼示例
示例備注:
- 基於vue、vant實現
- 請求后端api 獲取 JSDK授權信息需要根據自身情況做修改,字段如下:
wx.config({
debug: true, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印
appId: '', // 必填,公眾號的唯一標識
timestamp: , // 必填,生成簽名的時間戳
nonceStr: '', // 必填,生成簽名的隨機串
signature: '',// 必填,簽名
jsApiList: [], // 必填,需要使用的JS接口列表
openTagList: [] // 可選,需要使用的開放標簽列表,例如['wx-open-launch-app']
})
對於path屬性,所聲明的頁面路徑必須添加.html后綴,如pages/home/index.html。
開放標簽成功時才能看到button,僅真機測試有效。微信開發者工具無法展示button,且console提示錯誤[Vue warn]: Unknown custom element: <wx-open-launch-weapp> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
<template>
<div>
this is a demo
<div class="home">
<wx-open-launch-weapp
id="launch-btn"
:username="username"
:path="path"
@launch="handleLaunchFn"
@error="handleErrorFn"
>
<script type="text/wxtag-template">
<style>
.ant-btn {
line-height: 1.499;
position: relative;
display: inline-block;
font-weight: 400;
white-space: nowrap;
text-align: center;
background-image: none;
border: 1px solid #d9d9d9;
-webkit-box-shadow: 0 2px 0 rgba(0,0,0,0.015);
box-shadow: 0 2px 0 rgba(0,0,0,0.015);
cursor: pointer;
-webkit-transition: all .3s cubic-bezier(.645, .045, .355, 1);
transition: all .3s cubic-bezier(.645, .045, .355, 1);
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-ms-touch-action: manipulation;
touch-action: manipulation;
height: 32px;
padding: 0 15px;
font-size: 14px;
border-radius: 4px;
color: rgba(0,0,0,0.65);
background-color: #fff;
}
.ant-btn-red {
color: #fff;
background-color: #FF5A44;
border-color: #FF5A44;
text-shadow: 0 -1px 0 rgba(0,0,0,0.12);
-webkit-box-shadow: 0 2px 0 rgba(0,0,0,0.045);
box-shadow: 0 2px 0 rgba(0,0,0,0.045);
}
</style>
<button class="ant-btn ant-btn-red">{{ btnText }}</button>
</script>
</wx-open-launch-weapp>
</div>
</div>
</template>
<script>
import wx from 'weixin-js-sdk' // 引入weixin JSDK
import {Toast, Dialog, Notify} from 'vant'
// api 接口從后端獲取微信jsdk授權信息
import { getWechatJsConfig } from '../../../api/wechat'
export default{
data () {
return {
username: 'gh_xxxxxxxx', // gh_ 開頭的原始小程序ID
path: 'pages/index/index.html', // 一定要以 .html 結尾
btnText: "我的小程序"
}
},
methods: {
ToMiniapp() {
getWechatJsConfig({api: 'getLocation', 'url': window.location.href }).then(res => {
res['openTagList'] = ['wx-open-launch-weapp'] // 微信小程序標簽名加入 openTagList
console.log(res)
wx.config(res);
})
},
handleLaunchFn (e) {
console.log(e)
},
handleErrorFn(e){
console.log('fail', e.detail);
}
},
mounted() {
this.ToMiniapp()
}
}
</script>
