【HTMLだけ】広告なしQRコードリーダーをJavaScriptで作ってみた【ソースコード公開】
はじめに
以前公開した「広告なし・無料・インストール不要」のQRコードリーダーについて、「どのように作ったのですか?」「ソースコードを見てみたい」という声をいただきました。
そこで今回は、通常版のソースコードを公開します。今回は、通常版のソースコードを公開します。
このプログラムは、AIの手助けを受けながら設計・実装・改善を重ねて完成させたものです。
アイデアや画面構成、動作確認、使いやすさの調整は自分で行い、AIにはコード作成や改善の相談相手として協力してもらいました。
HTMLとJavaScriptだけで動作するため、サーバーを用意しなくてもブラウザだけで利用できます。
同じように「AIを活用して何かを作ってみたい」と考えている方の参考になれば幸いです。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>バーコードを よむ</title>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="バーコードを よむ">
<script src="https://unpkg.com/html5-qrcode"></script>
<style>
body {
font-family: 'Hiragino Kaku Gothic ProN', 'Meiryo', sans-serif;
text-align: center;
margin: 0;
padding: 20px;
background: #f7f9fa;
user-select: none;
}
h1 {
font-size: 26px;
color: #333;
margin-top: 10px;
margin-bottom: 5px;
}
.setsumei {
font-size: 20px;
font-weight: bold;
color: #555;
margin-bottom: 15px;
min-height: 30px;
}
/* カメラ枠 */
#reader {
width: 100%;
max-width: 450px;
margin: 0 auto;
background: white;
border: 5px solid #4CAF50;
border-radius: 16px;
overflow: hidden;
}
#reader button, #reader select {
display: none !important;
}
/* 結果表示エリア */
#result-box {
margin-top: 20px;
padding: 20px;
background: #ffffff;
border: 3px solid #ccc;
border-radius: 16px;
max-width: 450px;
margin-left: auto;
margin-right: auto;
box-shadow: 0 4px 10px rgba(0,0,0,0.05);
}
#result {
font-size: 32px;
font-weight: bold;
color: #333;
word-break: break-all;
margin: 10px 0;
}
/* ボタンの共通スタイル */
.go-btn {
display: none;
width: 100%;
max-width: 450px;
margin: 20px auto 0 auto;
padding: 24px;
font-size: 32px;
font-weight: bold;
color: white;
border: none;
border-radius: 16px;
cursor: pointer;
}
/* ひらくボタン(緑) */
#go-btn {
background-color: #2e7d32;
box-shadow: 0 8px #1b5e20;
}
#go-btn:active {
box-shadow: none;
transform: translateY(8px);
}
/* もう一度よみとるボタン(青) */
#retry-btn {
display: none;
background-color: #1565c0;
box-shadow: 0 8px #0d3c75;
}
#retry-btn:active {
box-shadow: none;
transform: translateY(8px);
}
</style>
</head>
<body>
<h1>バーコードを よむ</h1>
<p id="guide" class="setsumei">しかくのなかに うつしてください</p>
<div id="reader"></div>
<div id="result-box">
<div id="result">準備しています...</div>
</div>
<button id="go-btn" class="go-btn" onclick="openTargetUrl()">➔ ホームページをひらく</button>
<button id="retry-btn" class="go-btn" onclick="location.reload()">➔ もう一度よみとる</button>
<script>
let html5Qrcode = null;
let targetUrl = "";
let audioCtx = null;
// ピッ音を鳴らす関数
function playBeep() {
try {
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if (audioCtx && audioCtx.state === "suspended") {
audioCtx.resume().catch(() => {});
}
let osc1 = audioCtx.createOscillator();
let gain1 = audioCtx.createGain();
osc1.type = 'sine';
osc1.frequency.setValueAtTime(2000, audioCtx.currentTime);
gain1.gain.setValueAtTime(0.2, audioCtx.currentTime);
osc1.connect(gain1);
gain1.connect(audioCtx.destination);
osc1.start();
osc1.stop(audioCtx.currentTime + 0.05);
setTimeout(() => {
let osc2 = audioCtx.createOscillator();
let gain2 = audioCtx.createGain();
osc2.type = 'sine';
osc2.frequency.setValueAtTime(2000, audioCtx.currentTime);
gain2.gain.setValueAtTime(0.2, audioCtx.currentTime);
osc2.connect(gain2);
gain2.connect(audioCtx.destination);
osc2.start();
osc2.stop(audioCtx.currentTime + 0.05);
}, 60);
} catch (e) {
console.log("Audio error");
}
}
// カメラ起動
function startScanner() {
document.getElementById('result').innerText = "カメラをじゅんび しています";
document.getElementById('guide').innerText = "しかくのなかに うつしてください";
document.getElementById('go-btn').style.display = "none";
document.getElementById('retry-btn').style.display = "none";
targetUrl = "";
if (!html5Qrcode) {
html5Qrcode = new Html5Qrcode("reader");
}
const config = {
fps: 20,
qrbox: { width: 320, height: 140 },
experimentalFeatures: { useBarCodeDetectorIfSupported: true }
};
html5Qrcode.start(
{ facingMode: "environment" },
config,
onScanSuccess,
onScanFailure
).then(() => {
document.getElementById('result').innerText = "うつしてください";
}).catch(err => {
document.getElementById('result').innerText = "うつりません";
document.getElementById('retry-btn').style.display = "block";
});
}
// 読み取り成功時の処理
function onScanSuccess(decodedText, decodedResult) {
playBeep();
if (navigator.vibrate) { navigator.vibrate([100, 50, 100]); }
document.getElementById('guide').innerText = "よみとれました";
// カメラを完全に停止
html5Qrcode.stop().then(() => {
// 【洗練】最初にあらゆる余白(全角スペース含む)を綺麗にする
let text = decodedText.trim().replace(/\u3000/g, " ");
let isUrl = false;
let fixed = text;
// 【洗練】httpから始まらず、ドットがあり、メールやスペースがない場合に補完
if (
!/^https?:\/\//i.test(fixed) &&
fixed.includes(".") &&
!fixed.includes("@") &&
!fixed.includes(" ")
) {
fixed = "https://" + fixed;
}
// 最終的なURL判定
if (/^https?:\/\//i.test(fixed)) {
isUrl = true;
}
if (isUrl) {
try {
// 正しいURL形式か検証
new URL(fixed);
targetUrl = fixed;
// アプリストアのURLかチェック
const isAppStore = targetUrl.includes("apps.apple.com") || targetUrl.includes("play.google.com");
const goBtn = document.getElementById('go-btn');
if (isAppStore) {
document.getElementById('result').innerText = "アプリがみつかりました";
goBtn.innerText = "➔ アプリストアをひらく";
} else {
document.getElementById('result').innerText = "ホームページがみつかりました";
goBtn.innerText = "➔ ホームページをひらく";
}
// 0.3秒後に「ひらく」ボタンを表示
setTimeout(() => {
goBtn.style.display = "block";
}, 300);
} catch (e) {
// URL検証エラー時は「読み取りました:」をつけてテキスト表示
document.getElementById('result').innerText = "読み取りました:" + text;
}
} else {
// URLではない場合は「読み取りました:○○」とする
document.getElementById('result').innerText = "読み取りました:" + text;
}
// 0.3秒後に「もう一度よみとる」ボタンを表示
setTimeout(() => {
document.getElementById('retry-btn').style.display = "block";
}, 300);
}).catch(err => {
console.error(err);
// 【タフネス補強】二重エラーを防ぐ安全なクリーンアップ
try {
html5Qrcode.clear();
} catch(e) {}
});
}
function onScanFailure(error) {}
function openTargetUrl() {
if (targetUrl) {
window.location.href = targetUrl;
}
}
startScanner();
</script>
</body>
</html>