h5打开微信小程序
今天有一个新的需求,要求在h5页面打开外部的微信小程序页面,就简单写了一个demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="openwx">点击打开微信</button>
<script>
document.querySelector('.openwx').addEventListener('click', () => {
xhr.send({ "page": "pages/role/index" })
})
let xhr = new XMLHttpRequest();
xhr.open('get', "你的请求地址", true);
xhr.setRequestHeader("Content-Type", 'application/json');
xhr.onload = () => {
if (xhr.status == 200) {
console.log(xhr.responseText);
let list = JSON.parse(xhr.responseText)
let data = JSON.parse(list.data)
let times = new Date()
let url = data.url_link + "?time=" + times
//window.open(url) // 这里踩坑了 苹果的不允许这样操作
let a = document.createElement("a");
a.href = url;
a.click();
} else {
console.log("错误");
}
}
</script>
</body>
</html>
但是微信官方好像做了限制,现在的URL Scheme 和 URL Link只能被单用户访问,具体链接参考官方文档,这样就会造成一个问题,a用户访问之后b用户就不能访问了,解决方法如下,[以下代码来源于]([小程序URL Scheme规则调整支持方案_url scheme和url link_ziazan的博客-优快云博客](https://blog.youkuaiyun.com/FengNext/article/details/124078973?ops_request_misc=&request_id=&biz_id=102&utm_term=怎么保证微信小程序的URL Link能被多个人访问&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-1-124078973.142v93chatsearchT3_1&spm=1018.2226.3001.4187))
- 生成uuid
- 存储到localStorage
- 存到cookie
- 请求携带uuid
- 每次打开 先判断uuid有没有存在
function getUrlLink() {
const sessionCookie = getCookie('uuid');
let uuid = '';
if (!sessionCookie) {
uuid = localStorage.getItem('uuid');
if (!uuid) {
uuid = uuidV4(); // uuid
localStorage.setItem('uuid', 'uuid');
}
const effectiveTimeLen = 20 * 24 * 60 * 60 * 1000; // cookie过期时间20天
const expiresTime = new Date(Date.now() + effectiveTimeLen);
const cookieDomain = window.location.hostname.split('.').slice(-2).join('.');
document.cookie = `uuid=${uuid};expires=${expiresTime};path=/;domain=.${cookieDomain}`;
console.log("结果", `uuid=${uuid};expires=${expiresTime};path=/;domain=.${cookieDomain}`)
}
// 请求后台接口获取URL link
}
function getUuidV4() {
let t = Date.now()
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}) + '-' + t;
}
function getCookie(name) {
const strCookie = document.cookie;
const arrCookie = strCookie.split('; ');
for (let i = 0; i < arrCookie.length; i++) {
const arr = arrCookie[i].split('=');
if (arr[0] === name) {
return arr[1];
}
}
return '';
}