Using the Barcode Detection API to build a browser-based Web Barcode Scanner – a quick tutorial
Scanbot SDK
Wir bauen die schnellsten, genausten und verl?sslichsten L?sungen zur mobilen Datenerfassung für Ihre App oder Webseite.
The Barcode Detection API is a browser-native API for detecting and decoding barcodes in real time using a device’s camera or video input.
It is built directly into modern web browsers that support it. As such:
In this tutorial, we’ll show you how to build a web-based barcode scanner using the Barcode Detection API. This involves the following steps:
With the resulting web app, you can scan barcodes from your browser even without an internet connection.
Prerequisites
Ensure you have a browser that supports the Barcode Detection API (for example, Chrome, Edge). For more information about the supported browsers, see Browser compatibility.
To verify browser compatibility, open your browser’s console (DevTools) and type:
console.log("BarcodeDetector" in window); // Returns true if supported
If the result is false, switch to a supported browser.
At the time of writing, the API’s browser support is a follows:
The Barcode Detection API supports several barcode formats, including QR codes, EAN-13, Code 128, and more. For more information about the supported formats, see Supported barcode formats.
Step 1: Set up the project
Create a folder for your project and name it, e.g., “web-barcode-scanner”.
mkdir web-barcode-scanner
Step 2: Create the source files
Create the following files in your web-barcode-scanner project folder:
Step 3: Define the HTML structure
In the index.html file, define the structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Barcode Scanner</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Web Barcode Scanner</h1>
<video id="video" autoplay></video>
<div id="result">Scanned Barcode: <span id="barcodeResult">None</span></div>
<script src="index.js"></script>
</body>
</html>
This structure includes a video element to display the camera feed and a section to display the scanned barcode result.
Step 4: Add style in CSS
In the style.css file, style the components for a clean and user-friendly interface:
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 0;
background-color: #f9f9f9;
}
h1 {
color: #333;
}
video {
width: 80%;
max-width: 600px;
border: 2px solid #333;
border-radius: 8px;
margin: 20px auto;
display: block;
}
#result {
font-size: 1.2rem;
margin-top: 10px;
}
Step 5: Implement the JavaScript code
The index.js file should contain the JavaScript code to initialize the Barcode Detection API and manage the logic for the barcode scanning process.
(async function () {
const video = document.getElementById("video");
const barcodeResult = document.getElementById("barcodeResult");
// Check for BarcodeDetector support
if (!("BarcodeDetector" in window)) {
alert("Barcode Detection API is not supported in this browser.");
return;
}
// Initialize the Barcode Detector with supported formats
const barcodeDetector = new BarcodeDetector({ formats: ["qr_code", "ean_13", "code_128"] });
try {
// Access the camera
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
video.srcObject = stream; // Assign stream to video element
video.play();
// Barcode detection loop
video.addEventListener("play", async () => {
while (true) {
try {
const barcodes = await barcodeDetector.detect(video); // Detect barcodes
if (barcodes.length > 0) {
barcodeResult.textContent = barcodes[0].rawValue; // Show first detected barcode
}
} catch (err) {
console.error("Error detecting barcode:", err);
}
await new Promise(resolve => setTimeout(resolve, 100)); // Add delay for performance
}
});
} catch (error) {
console.error("Error accessing camera:", error);
alert("Unable to access the camera. Please check permissions or run the code on a secure server.");
}
})();
The script first ensures the Barcode Detection API is supported in the current browser. If not, it alerts the user and stops further execution.
Then, it creates a new instance of BarcodeDetector and specifies the barcode formats to detect, in this case QR?Code, EAN-13, and Code?128.
The script then requests access to the device’s camera using getUserMedia.
The script uses the detect() method to scan barcodes from the video feed and display the result.
If a barcode is detected, its value (rawValue) is displayed in the barcodeResult element.
Step 6: Test the application
Open your index.html file in a web browser. Ensure your browser allows camera access, and when prompted, grant permission.
When the camera detects a barcode in the camera feed, its value is displayed below the video frame.
Disadvantages of using the Barcode Detection?API
The Barcode Detection?API is a useful tool for simple barcode scanning use cases. However, it has its limitations:
For companies that heavily rely on barcode scanning in their business processes, we recommend using an enterprise-grade solution instead.
Building a JavaScript-based Web Barcode Scanner with the Scanbot?SDK
We developed the Scanbot?Barcode Scanner?SDK to help enterprises overcome the hurdles presented by free barcode scanning software. Our goal was to have a developer-friendly solution available for a wide range of platforms that consistently delivers high-quality results – even in challenging circumstances.
Scan the QR code or follow this link to try the Web Barcode Scanner Demo!
In the following section, we’ll show you how easy it is to integrate our Web Barcode Scanner?SDK into your JavaScript app. Thanks to our SDK’s Ready-to-Use UI Components, you can even use an AR?overlay to display multiple barcodes’ contents right in the viewfinder.
To accomplish that, we’ll need to follow the steps below:
Let’s dive into more details for each step.
Step 1: Download the SDK
First, create a new empty directory for your app and name it my-scanner-app.
Then, download the Scanbot?SDK npm package directly from here.
?? As specified in our documentation, you can also use npm install to download and install the package, but for this tutorial, we suggest manually downloading it and installing it from the link provided.
Unzip the downloaded files into my-scanner-app. Your folder structure should look like this:
my-scanner-app/
? |- scanbot-web-sdk/
? ? |- webpack/
? ? |- bundle/
? ? |- @types/
? ? |- index.js
? ? |- ui.js
? ? ... (and some other files)
?? Make sure the folder containing the package files is called scanbot-web-sdk, not “package” or similiar.
Step 2: Create the HTML page and configure the Web?SDK
To create the HTML with the Scanbot?SDK, first create an index.html file in the my-scanner-app/ folder. Then, add the following code to the file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- We prevent the user from zooming on mobile device -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<title>My Scanner App</title>
</head>
<body style="margin: 0">
<button id="start-scanning">Start scanning</button>
<pre id="result"></pre>
<script type="module">
// We import the necessary ScanbotSDK module
import "./scanbot-web-sdk/bundle/ScanbotSDK.ui2.min.js";
// When initializing the SDK, we specify the path to the barcode scanner engine
const sdk = await ScanbotSDK.initialize({
engine: "scanbot-web-sdk/bundle/bin/barcode-scanner/"
});
document.getElementById("start-scanning").addEventListener("click", async () => {
// We create a new default configuration for the barcode scanner
const config = new ScanbotSDK.UI.Config.BarcodeScannerConfiguration();
// We create a barcode scanner UI component
const scanResult = await ScanbotSDK.UI.createBarcodeScanner(config);
// Once the scanning is done, we display the result
if (scanResult?.items?.length > 0) {
document.getElementById("result").innerText =
`Barcode type: ${scanResult.items[0].type} \n` +
`Barcode content: "${scanResult.items[0].text}" \n`;
} else {
document.getElementById("result").innerText = "Scanning aborted by the user";
}
});
</script>
</body>
</html>
The code block above:
Step 3: Start local HTTP server?
The Scanbot?SDK uses advanced browser features that are unavailable when opening our site via a file URL. Therefore, a local HTTP server is required to view the site.
There are two main ways to run the index.js file in a localhost server: using Python or Node.js.
Python
If you have Python installed, you can use it to start a local HTTP server. To do so, follow the steps below:
To stop running the localhost server, press Ctrl+C on the terminal.
Node.js
If Node.js is installed, you can use the npm serve package to start a local HTTP server. To do so, follow the steps below:
To stop running the localhost server, press Ctrl+C on the terminal.
Step 4: Start scanning
Once you access the site on your browser, follow the steps below to test the Scanbot?SDK:
Click the “Start scanning” button.
The scanning UI will open, allowing you to scan a barcode using your camera. Point your camera to a barcode, as in the example below.
The default scanning screen
After scanning, the UI closes, displaying the scanned code and its type right below the “Start scanning” button.
A straightforward way of displaying a barcode’s type and content
Step 5: Configure the style and scanning behavior
The app code provided in Step 2 has the UI fully configured. To change the app’s appearance, you can customize the config object. You can, for example, change the viewfinder size and color.
To do so, you can change the aspectRatio and strokeColor after defining the config object, as displayed in the following code block:
const config = new ScanbotSDK.UI.Config.BarcodeScannerConfiguration();
config.viewFinder.aspectRatio.height = 1;
config.viewFinder.aspectRatio.width = 5;
config.viewFinder.style.strokeColor = "#FF000050";
The above configurations will result in the following styling:
A more horizontal version of the viewfinder with red corners
You can find more configuration options by accessing the SDK or API documentation.
As another configuration example, you can display an AR overlay and let the user pick a specific barcode when the app identifies multiple barcodes on the camera. To add this feature, add the following code after defining the config object:
config.useCase.arOverlay.visible = true;
config.useCase.arOverlay.automaticSelectionEnabled = false;
If you open your app again, it will look like this:
The AR overlay displays the barcodes’ contents right in the viewfinder
?? The AR labels can also be fully configured.
Step 6: Deploy to a server (optional)
To test your new app on your phone, you need to deploy it to a server. If you don’t have a web server ready, you can prototype your site using services like Static.app by executing the following steps:
The Scanbot?SDK UI is optimized for mobile devices. It allows users to choose the camera and toggle the flashlight by default. Use the URL to test the app interface on your mobile device, as displayed below.
Our JavaScript barcode scanner running on a phone
Conclusion
That’s it! You now have a fully functional barcode-scanning web app using the Scanbot?SDK’s RTU UI.
You can also take a look at our integration guides for React and Vue.js for implementations similar to this one. Should you have any questions, feel free to reach out to us on Slack or MS Teams or send us an email via [email protected]