
【Google Apps Script】完全初心者でも作れる!バーコードPOSシステム 第2回:バーコード読み取り機能編
はじめに
第1回では、Google Apps Scriptの環境構築を行いました。
今回は、いよいよWebアプリの作成に入ります。スマホやタブレットのカメラでバーコードを読み取り、Googleスプレッドシートに自動記録する機能を作ります。
この回で作るもの:
カメラでバーコード読み取り
数量入力(±対応)
登録ボタン
スプレッドシートへの自動記録
完成したら、スマホからアクセスして実際に動かしてみましょう!
このシリーズはこちら
Webアプリの仕組み
Google Apps Scriptで作るWebアプリは、大きく2つのパーツで構成されています。
1. HTML(見た目・入力画面)
ユーザーが操作する画面です。
カメラ起動ボタン
バーコード表示欄
数量入力欄
登録ボタン
2. GAS(処理・データ保存)
HTMLから送られてきたデータを受け取り、スプレッドシートに書き込みます。
流れ:
スマホでカメラ起動(HTML)
↓
バーコード読み取り
↓
数量調整
↓
登録ボタンタップ
↓
GASが受信・処理
↓
スプレッドシートに記録
ステップ1:HTMLファイルを作成
まずは、ユーザーが操作する画面(HTML)を作ります。
1-1. 新しいHTMLファイルを追加
Apps Scriptエディタを開く(前回作ったプロジェクト)
左側のファイル一覧の横にある「+」ボタンをクリック
「HTML」を選択
ファイル名を 「index」 にする(拡張子.htmlは自動で付きます)
1-2. HTMLコードを書く
index.html を開いて、中身をすべて削除してから、以下のコードを丸ごとコピー&ペーストしてください。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>バーコードPOS</title>
<script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2@1.7.0/dist/quagga.min.js"></script>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: sans-serif;
background: #f0f2f5;
display: flex;
justify-content: center;
padding: 20px;
}
.container {
background: #fff;
border-radius: 12px;
padding: 24px;
width: 100%;
max-width: 480px;
box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}
h1 { font-size: 20px; text-align: center; margin-bottom: 24px; color: #333; }
#interactive {
width: 100%;
height: 240px;
background: #000;
border-radius: 8px;
overflow: hidden;
margin-bottom: 16px;
display: none;
}
#interactive video { width: 100%; height: 100%; object-fit: cover; }
#interactive canvas { display: none; }
.btn {
width: 100%;
padding: 12px;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
margin-bottom: 12px;
}
.btn-camera { background: #4CAF50; color: #fff; }
.btn-camera.active { background: #f44336; }
.btn-submit { background: #2196F3; color: #fff; }
.btn-submit:disabled { background: #ccc; cursor: not-allowed; }
label { display: block; font-size: 14px; color: #666; margin-bottom: 4px; }
input[type="text"], input[type="number"] {
width: 100%;
padding: 10px 12px;
border: 1px solid #ddd;
border-radius: 8px;
font-size: 16px;
margin-bottom: 16px;
}
.quantity-control {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 16px;
}
.quantity-control input {
flex: 1;
text-align: center;
margin-bottom: 0;
}
.btn-qty {
width: 44px;
height: 44px;
border: none;
border-radius: 8px;
font-size: 20px;
cursor: pointer;
background: #e0e0e0;
color: #333;
flex-shrink: 0;
}
#message {
text-align: center;
padding: 10px;
border-radius: 8px;
font-size: 14px;
margin-bottom: 12px;
display: none;
}
#message.success { background: #e8f5e9; color: #2e7d32; display: block; }
#message.error { background: #ffebee; color: #c62828; display: block; }
</style>
</head>
<body>
<div class="container">
<h1>📦 バーコードPOS</h1>
<div id="interactive"></div>
<button class="btn btn-camera" id="cameraBtn" onclick="toggleCamera()">
📷 カメラ起動
</button>
<label>JANコード</label>
<input type="text" id="barcode" placeholder="バーコードを読み取るか直接入力">
<label>数量(出庫はマイナスで入力)</label>
<div class="quantity-control">
<button class="btn-qty" onclick="adjustQuantity(-1)">-</button>
<input type="number" id="quantity" value="1">
<button class="btn-qty" onclick="adjustQuantity(1)">+</button>
</div>
<div id="message"></div>
<button class="btn btn-submit" id="submitBtn" onclick="submitData()">
✅ 登録
</button>
</div>
<script>
let scanning = false;
function toggleCamera() {
if (scanning) {
stopCamera();
} else {
startCamera();
}
}
function startCamera() {
const viewer = document.getElementById('interactive');
viewer.style.display = 'block';
Quagga.init({
inputStream: {
type: 'LiveStream',
target: viewer,
constraints: { facingMode: 'environment' }
},
decoder: {
readers: ['ean_reader', 'ean_8_reader', 'code_128_reader']
}
}, function(err) {
if (err) {
showMessage('カメラの起動に失敗しました。ブラウザの許可設定を確認してください。', 'error');
viewer.style.display = 'none';
return;
}
Quagga.start();
scanning = true;
const btn = document.getElementById('cameraBtn');
btn.textContent = '⏹ カメラ停止';
btn.classList.add('active');
});
Quagga.onDetected(function(result) {
const code = result.codeResult.code;
document.getElementById('barcode').value = code;
playBeep();
stopCamera();
});
}
function stopCamera() {
Quagga.stop();
scanning = false;
const viewer = document.getElementById('interactive');
viewer.style.display = 'none';
const btn = document.getElementById('cameraBtn');
btn.textContent = '📷 カメラ起動';
btn.classList.remove('active');
}
function adjustQuantity(delta) {
const input = document.getElementById('quantity');
input.value = parseInt(input.value || 0) + delta;
}
function playBeep() {
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.connect(gain);
gain.connect(ctx.destination);
osc.frequency.value = 880;
gain.gain.setValueAtTime(0.3, ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.3);
osc.start(ctx.currentTime);
osc.stop(ctx.currentTime + 0.3);
}
function showMessage(text, type) {
const el = document.getElementById('message');
el.textContent = text;
el.className = type;
setTimeout(() => { el.className = ''; el.style.display = 'none'; }, 3000);
}
function submitData() {
const barcode = document.getElementById('barcode').value.trim();
const quantity = parseInt(document.getElementById('quantity').value);
if (!barcode) {
showMessage('JANコードを入力してください', 'error');
return;
}
if (isNaN(quantity) || quantity === 0) {
showMessage('数量を正しく入力してください', 'error');
return;
}
const btn = document.getElementById('submitBtn');
btn.disabled = true;
btn.textContent = '送信中...';
google.script.run
.withSuccessHandler(function() {
showMessage('✅ 登録しました!', 'success');
document.getElementById('barcode').value = '';
document.getElementById('quantity').value = '1';
btn.disabled = false;
btn.textContent = '✅ 登録';
})
.withFailureHandler(function(err) {
showMessage('❌ エラー:' + err.message, 'error');
btn.disabled = false;
btn.textContent = '✅ 登録';
})
.recordData(barcode, quantity);
}
</script>
</body>
</html>
コードのポイント解説
使用しているライブラリ:
<script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2@1.7.0/dist/quagga.min.js"></script>
QuaggaJS2という無料のバーコード読み取りライブラリです。JAN/EAN-13・EAN-8・CODE128に対応しています。インストール不要で、このタグを1行書くだけで使えます。
カメラ起動部分:
Quagga.init({
inputStream: {
type: 'LiveStream',
target: viewer,
constraints: { facingMode: 'environment' } // 背面カメラを指定
},
decoder: {
readers: ['ean_reader', 'ean_8_reader', 'code_128_reader'] // 対応バーコード形式
}
}, ...
facingMode: 'environment' で背面カメラを指定しています。スマホの内カメラではなく外カメラでスキャンするための設定です。
バーコード検出部分:
Quagga.onDetected(function(result) {
const code = result.codeResult.code;
document.getElementById('barcode').value = code;
playBeep(); // ビープ音を鳴らす
stopCamera(); // 読み取り後は自動でカメラ停止
});
バーコードを認識すると、自動でJANコード欄に入力されます。ビープ音が鳴ってカメラが止まるので、読み取れたかどうかがわかりやすくなっています。
スプレッドシートへの送信部分:
google.script.run
.withSuccessHandler(function() { ... })
.withFailureHandler(function(err) { ... })
.recordData(barcode, quantity);
google.script.run はGASのWebアプリ専用の仕組みで、HTML側からGAS側の関数を呼び出せます。recordData が次のステップで書くGAS関数です。
ステップ2:GASコードを書く
次に、HTMLから送られてきたデータを受け取り、スプレッドシートに書き込む処理を作ります。
2-1. コード.gsを開く
左側のファイル一覧から「コード.gs」をクリックします。
2-2. GASコードを書く
中身をすべて削除してから、以下のコードを丸ごとコピー&ペーストしてください。
// Webアプリを表示する関数
function doGet() {
return HtmlService.createHtmlOutputFromFile('index')
.setTitle('バーコードPOS')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
// データを記録する関数(HTMLから呼び出される)
function recordData(barcode, quantity) {
try {
// スプレッドシートの「入出庫記録」シートを取得
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('入出庫記録');
// 現在日時を取得
const now = new Date();
// 最終行にデータを追加
sheet.appendRow([now, barcode, quantity]);
return '登録成功';
} catch (error) {
throw new Error('データ記録に失敗しました: ' + error.toString());
}
}
コードの解説:
doGet() はWebアプリにアクセスされたときに自動で呼ばれる特別な関数です。index.html を画面として表示する役割を持っています。
recordData() はHTMLの「登録ボタン」を押したときに呼ばれる関数です。引数で受け取ったJANコードと数量を、スプレッドシートの末尾に追記します。
ステップ3:Webアプリを公開する
作成したWebアプリを、スマホからアクセスできるようにします。
3-1. デプロイ(公開)
エディタ右上の「デプロイ」ボタンをクリック
「新しいデプロイ」を選択
「種類の選択」(歯車アイコン)をクリック
「ウェブアプリ」を選択
3-2. 設定
項目 設定値 説明 バーコードPOSシステム v1.0 次のユーザーとして実行 自分 アクセスできるユーザー 全員
「デプロイ」ボタンをクリックします。
3-3. URLをコピー
「ウェブアプリ URL」が表示されます。
https://script.google.com/macros/s/●●●●●/exec
このURLをコピーしてください。これがあなたのバーコードPOSシステムのアドレスです。
ステップ4:動作確認
4-1. スマホでアクセス
スマホのブラウザ(SafariやChromeなど)を開く
コピーしたURLを貼り付けてアクセス
初回のみ「承認が必要です」と表示されるので許可する
バーコードPOSの画面が表示されます!
4-2. カメラでバーコード読み取り
「📷 カメラ起動」ボタンをタップ
カメラ使用の許可を求められたら「許可」
商品のバーコードにカメラを向ける
自動でJANコードが読み取られ、入力欄に表示される
「ピッ」とビープ音が鳴りカメラが止まる
4-3. 数量調整と登録
「+」「-」ボタンで数量を調整(出庫はマイナスにする)
「✅ 登録」ボタンをタップ
「✅ 登録しました!」と表示されれば成功
4-4. スプレッドシートを確認
Googleスプレッドシートを開いて「入出庫記録」シートを確認してください。
日時 | JANコード | 数量
2025/12/13 14:30:00 | 4901234567890 | 5
2025/12/13 14:32:00 | 4901234567890 | -3
このようにデータが記録されていれば完成です🎉
便利な使い方
ホーム画面に追加
スマホのブラウザで「ホーム画面に追加」すると、アプリのように使えます。
iPhone(Safari):
画面下の共有ボタン(四角から矢印が出ているアイコン)をタップ
「ホーム画面に追加」を選択
Android(Chrome):
右上のメニュー(︙)をタップ
「ホーム画面に追加」を選択
出庫の記録
出庫の場合は「-」ボタンで数量をマイナスにします。
例:5個出庫する場合
バーコードを読み取る
「-」ボタンを4回タップして「-3」にする(最初が1なので)
「✅ 登録」をタップ
数値を直接キーボードで入力することもできます。
トラブルシューティング
Q1. カメラが起動しない
ブラウザのカメラ使用許可を確認してください。iPhoneの場合は「設定 → Safari → カメラ → 許可」です。Google Apps ScriptのURLはHTTPSなので、カメラの使用自体は問題なく行えます。
Q2. バーコードが読み取れない
明るい場所で、バーコードとカメラの距離を15〜30cm程度に保って試してください。バーコードが汚れていたり折れ曲がっていると読み取りにくくなります。
Q3. 登録ボタンを押してもエラーになる
スプレッドシートのシート名が「入出庫記録」になっているか確認してください。スペルが1文字でも違うとエラーになります。
Q4. コードを変更したのに反映されない
GASのコードを変更した場合は、必ず「新しいデプロイ」または「デプロイを管理→編集→バージョン新規作成」で再デプロイしてください。コードを保存しただけでは公開中のWebアプリには反映されません。
今回のまとめ
やったこと: ✅ HTMLでカメラ読み取り画面を作成 ✅ QuaggaJS2ライブラリでバーコード認識 ✅ GASでデータ受信・スプレッドシート記録処理を実装 ✅ Webアプリを公開 ✅ スマホから動作確認
これで、スマホのカメラでバーコードを読み取ってデータを記録できるようになりました!
次回予告: 第3回では、記録データの自動リセットとExcelとの連携に入ります。
毎日0時に自動でデータをクリア
スプレッドシートからExcelへのデータ移行
VBAで自動集計の準備
より実用的なシステムに進化させていきます。お楽しみに!