讓 Line Liff 順利掃描 QRCODE
Liff 的眾多功能中有一個超棒的功能 scanCode
不過很不幸的一推出就被宣告不能使用,正所謂出師未捷身先死。
天無絕人之路,我們可以利用 WebRTC 的技術來達成在 Liff 中掃描 QRCode 的功能。想知道技術細節的可以點超連結過去看維基百科。
搜尋了一下,也已經有大神開發出套件可以讓我們套用了。讓我們開始吧!
附帶一提:2021-05-20 我在github 下載的這個版本 js 有點問題是無法使用的。想要使用的人可以試試看 html5-qrcode cdn
首先我們先在 body 中建立一個 div
<div id="reader" style="width:500px;height:500px;"></div>
接著就是 JS 的部分了
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.0.1/html5-qrcode.min.js" integrity="sha512-JXdlXFkKGAhP2yUubNT7hXNjEtPrAJz1Gs7oztdP47KhqL5ux88uof5FnIm2D0Ud/TdqiAe1mM1179kJDy/HKA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
// This method will trigger user permissions
Html5Qrcode.getCameras().then(devices => {
/**
* devices would be an array of objects of type:
* { id: "id", label: "label" }
*/
if (devices && devices.length) {
var cameraId = devices[1].id; // 取得攝影機編號 devices[1] 是後置攝影機, devices[0] 是前置
// .. use this to start scanning.
const html5QrCode = new Html5Qrcode(/* element id */ "reader");
html5QrCode.start(
cameraId,
{
fps: 10, // Optional frame per seconds for qr code scanning
qrbox: 300 // Optional if you want bounded box UI
},
qrCodeMessage => {
// 有掃到資料就彈出內容
alert(qrCodeMessage)
},
errorMessage => {
// parse error, ignore it.
})
.catch(err => {
// Start failed, handle it.
});
}
}).catch(err => {
// 載入攝影機失敗
});
</script>



留言
張貼留言