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:
- No external libraries or installations are required.
- All functionality is provided through the browser’s JavaScript engine.
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:
- Setting up the project
- Creating the source files
- Defining the HTML structure
- Adding style in CSS
- Implementing the JavaScript code
- Testing the application
With the resulting web app, you can scan barcodes from your browser even without a 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:
Chrome Android | ✅ fully supported |
Opera Android | ✅ fully supported |
WebView Android | ✅ fully supported |
Samsung Internet | ✅ fully supported |
Chrome | ➖ partly supported |
Edge | ➖ partly supported |
Opera | ➖ partly supported |
Firefox | ❌ not supported |
Firefox Android | ❌ not supported |
Safari | ❌ not supported |
Safari iOS | ❌ not supported |
WebView iOS | ❌ not supported |
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:
- index.html: The HTML structure
- style.css: The styling file
- index.js: The JavaScript logic
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
.
{ facingMode: "environment" }
ensures the use of the rear camera, which is the preferred camera for scanning barcodes due to its higher resolution.- The camera feed (stream) is assigned to the
<video>
element so it displays the live video. video.play()
starts playing the video feed.
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:
- Limited Browser compatibility: The Barcode Detection API only works in a handful of browsers and doesn’t support Firefox or Safari. This severely limits its flexibility.
- Lackluster performance on mobile devices: Users have reported that the Barcode Detection API works on some mobile devices but not others. They’ve also reported issues with the auto-focus. The inconsistent performance makes the API hard to recommend for multi-platform applications.
- Small number of supported barcodes: The API supports some of the most commonly used barcode types like Code 128, QR Code, and PDF417, but lacks support for industry-specific symbologies like IATA 2 of 5 and 4-State-Customer Codes. This limits the API’s usefulness for companies in those industries.
- Slow scanning speed: The API’s barcode recognition and data extraction speed is comparatively slow. This is less of a problem if users only need to scan a single barcode, but quickly adds up when many barcodes need to be scanned successively.
- Low performance in poor conditions: While scanning barcodes works well enough in optimal conditions, the API’s performance decreases significantly if the barcodes are poorly lit, damaged, or far away. If you need to scan barcodes in varying conditions, an alternative solution using machine learning is the more viable option.
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:
- Download the SDK files
- Create the HTML page and configure the Web SDK
- Start a local HTTP server
- Start scanning
- Configure styling and scanning behavior
- Deploy to a server (optional)
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:
- Adds the “Start scanning” button.
- Imports and initializes the Scanbot SDK.
- Executes the user interface from the Scanbot SDK when the user clicks the “Start scanning” button.
- If a barcode is identified, it will present the barcode type and its content to the user.
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:
- Open a terminal in the my-scanner-app/ folder.
- Use the command
python3 -m http.server
to start a local test server. - Now, you can access it on your browser at
http://localhost:8000
.
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:
- Open a terminal in the my-scanner-app/ folder.
- Run the command
npx serve
. - Once it finishes loading, you can access the page using the URL provided in your terminal, which usually is
http://localhost:3000
.
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.
Our simple start screen
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:
- Zip the content from my-scanner-app.
- Access Static.app and click Upload for free.
- Find and select the my-scanner-app.zip file.
- After the upload, your site will run within minutes. You will then be presented with a URL. Use it to access the app from any device, including your mobile phone.
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 sdksupport@scanbot.io