微信小程序摄像头组件识别 URL Link

微信小程序摄像头组件识别 URL Link

这是之前的存稿,是否受新版调整需自己测试。https://mp.weixin.qq.com/s/gQhIWCcxxHAGc_4-nzGesw

1
2
3
4
<!--index.wxml-->
<view class="container">
<camera mode="scanCode" resolution="high" device-position="back" flash="off" frame-size="large" style="width: 100vw; height: 100vh;" bindscancode="handleScanCode"></camera>
</view>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// index.js

Page({
data: {},
onShow () {
// this.handleScanCode({
// detail: {
// result: 'https://wxaurl.cn/pFawq35qbfd',
// },
// });
},
// 扫码成功处理
handleScanCode({ detail }) {
// detail = {
// charSet: "UTF-8",
// rawData: "aHR0cHM6Ly93eGF1cmwuY24vcEZhd3EzNXFiZmQ=",
// result: "https://wxaurl.cn/pFawq35qbfd",
// scanArea: [72, 188, 83, 92],
// type: "QR_CODE"
// };

const { result } = detail;

// 判断识别到的是不是指定的两个网址前缀
if (result.indexOf('https://wxaurl.cn') !== 0 && result.indexOf('https://wxmpurl.cn/') !== 0) {
return wx.showToast({
title: '无法处理[' + result + ']',
icon: 'none',
});
}

// 请求网址获取数据
return wx.request({
url: result, // 记得两个域名要加入白名单
success: (response) => {
if (response.statusCode !== 200) {
return wx.showToast({
title: '读取失败[HTTP ' + response.statusCode + ']',
icon: 'none',
});
}

const html = response.data;

// 计算开始截取的位置
const index = html.indexOf('window.data = {');

// 截取出内容
var data = html.substr(index + 'window.data = '.length, html.indexOf('}', index) - index - 'window.data = '.length + 1);
// data = `{
// head_img_url: 'http://wx.qlogo.cn/mmhead/Q3auHgzwzM7Fll3F71bOWuUvJCZWo1yia2gtXmiaDMcAC0hIsAgJ2UlQ/132',
// nickname: '小程序示例',
// url_scheme: 'weixin://dl/business/?t=pFawq35qbfd',
// user_name: 'gh_d43f693ca31f',
// path: 'page/cloud/index',
// query: '0',
// }`;

// 将key和value不带双引号的JSON字符串转换成JSON对象的方法
// https://my.oschina.net/u/4303162/blog/3365199
data = data.replace(/(\s*?{\s*?|\s*?,\s*?)(['"])?([a-zA-Z0-_9]+)(['"])?:/g, '$1"$3":');
// 将单引号替换成双引号
data = data.replace(/'/g, '"');
// 去除 query 这行最后面的逗号
data = data.replace(/query(.*),/g, 'query$1');
// 解析
data = JSON.parse(data);

// 如果存在 = 则需要进行解析参数,这个看情况。
if(data.query.indexOf('=') !== -1) {
const query = {};
const query_tmp = data.query.split('&');

for(let i in query_tmp) {
let query_item = query_tmp[i].split('=');
query[query_item[0]] = query_item[1];
}

data.query = query;
}

// 结果
// data = {
// head_img_url: "http://wx.qlogo.cn/mmhead/Q3auHgzwzM7Fll3F71bOWuUvJCZWo1yia2gtXmiaDMcAC0hIsAgJ2UlQ/132",
// nickname: "小程序示例",
// path: "page/cloud/index",
// query: "0", // 不存在可解析的参数
// query: { // 存在可解析的参数
// hongfs: "hongfs",
// },
// url_scheme: "weixin://dl/business/?t=pFawq35qbfd",
// user_name: "gh_d43f693ca31f"
// };

console.log('data', data);
},
})
},
});

文档

获取 URL Link

往上