Search code examples
javascriptzxingjsbarcode

JsBarcode is not a function, Uncaught (in promise) Object, require is not defined, ZXing is not defined


I can't get this javascript code to work right, it keeps giving me errors.

This is my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Barcode Generator and Scanner</title>
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode"></script>
    <script src="https://unpkg.com/@zxing/browser@latest"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .container {
            margin-bottom: 20px;
        }
        video {
            width: 100%;
            max-width: 400px;
        }
        svg {
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <h1>Barcode Generator and Scanner</h1>
    
    <!-- Barcode Generator -->
    <div class="container">
        <h2>Generate Barcode</h2>
        <label for="rewardsLevel">Rewards Level:</label>
        <select id="rewardsLevel">
            <option value="1">Silver</option>
            <option value="2">Gold</option>
            <option value="3">Platinum</option>
        </select><br>
        <label for="email">Email:</label>
        <input type="email" id="email" placeholder="example@gmail.com"><br>
        <label for="issueDate">Issue Date:</label>
        <input type="date" id="issueDate"><br>
        <label for="name">Name:</label>
        <input type="text" id="name" placeholder="Your Name"><br><br>
        <button onclick="generateBarcode()">Generate Barcode</button>
        <svg id="barcode"></svg>
        <button id="downloadBarcode" onclick="downloadSVG()" style="display:none;">Download Barcode</button>
    </div>

    <!-- Barcode Scanner -->
    <div class="container">
        <h2>Scan Barcode</h2>
        <button onclick="startScanner()">Start Scanner</button>
        <button onclick="resetScanner()">Reset Scanner</button>
        <video id="video" autoplay muted playsinline></video>
        <div id="decodedOutput" style="margin-top: 20px;"></div>
    </div>

    <script>
        // Barcode Generator
        function generateBarcode() {
            const rewardsLevel = document.getElementById("rewardsLevel").value;
            const email = document.getElementById("email").value;
            const issueDate = document.getElementById("issueDate").value.replace(/-/g, '');
            const name = document.getElementById("name").value;

            if (!email || !issueDate || !name) {
                alert("Please fill in all fields.");
                return;
            }

            const barcodeValue = `${rewardsLevel}*${issueDate}*${email}*${name}`;
            const barcodeElement = document.getElementById("barcode");

            JsBarcode(barcodeElement, barcodeValue, {
                format: "CODE128",
                width: 2,
                height: 100,
                displayValue: true
            });

            document.getElementById("downloadBarcode").style.display = "block";
        }

        // Download Barcode
        function downloadSVG() {
            const svg = document.getElementById("barcode");
            const serializer = new XMLSerializer();
            const source = serializer.serializeToString(svg);
            const blob = new Blob([source], { type: "image/svg+xml;charset=utf-8" });
            const url = URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = url;
            link.download = "barcode.svg";
            link.click();
            URL.revokeObjectURL(url);
        }

        // Barcode Scanner
        let codeReader;
        const videoElement = document.getElementById("video");

        async function startScanner() {
            if (!codeReader) {
                codeReader = new ZXing.BrowserMultiFormatReader();
            }
            const devices = await codeReader.listVideoInputDevices();
            if (devices.length === 0) {
                alert("No video input devices found.");
                return;
            }

            const selectedDeviceId = devices[0].deviceId;
            codeReader.decodeFromVideoDevice(selectedDeviceId, videoElement, (result, error) => {
                if (result) {
                    displayDecodedData(result.text);
                    codeReader.reset(); // Stop scanning once a code is detected
                }
                if (error) {
                    console.error(error);
                }
            });
        }

        function displayDecodedData(data) {
            const [level, date, email, name] = data.split('*');
            const levels = { "1": "Silver", "2": "Gold", "3": "Platinum" };
            const formattedDate = new Date(date.substring(0, 4), date.substring(4, 6) - 1, date.substring(6, 8))
                .toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });

            const outputDiv = document.getElementById("decodedOutput");
            outputDiv.innerHTML = `
                <p><strong>Rewards Level:</strong> ${levels[level]}</p>
                <p><strong>Issue Date:</strong> ${formattedDate}</p>
                <p><strong>Email:</strong> ${email}</p>
                <p><strong>Name:</strong> ${name}</p>
            `;
        }

        function resetScanner() {
            if (codeReader) {
                codeReader.reset();
            }
            videoElement.srcObject = null;
            document.getElementById("decodedOutput").innerHTML = "";
        }
    </script>
</body>
</html>

And i get these errors when i run it:

Uncaught ReferenceError: require is not defined
JsBarcode.js:3:17

Uncaught (in promise) Object
card:1

Uncaught (in promise) Object
browser-polyfill.min.js:1

Uncaught (in promise) Object
iframefallback:1

Uncaught (in promise) Object
card:1

Uncaught (in promise) Object
browser-polyfill.min.js:1

Uncaught TypeError: JsBarcode is not a function
card:526

TypeError: JsBarcode is not a function
web.assets_frontend_lazy.min.js:4107

ReferenceError: ZXing is not defined
card:556

Solution

  • You just need a different version of jsbarcode. Try:

    https://cdn.jsdelivr.net/npm/jsbarcode@3.11.0/dist/JsBarcode.all.min.js
    

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Barcode Generator and Scanner</title>
        <!--
            EDIT Replace this version of jsbarcode with the one below.
            <script src="https://cdn.jsdelivr.net/npm/jsbarcode"></script>
        -->
        <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.0/dist/JsBarcode.all.min.js"> </script>
        <script src="https://unpkg.com/@zxing/browser@latest"></script>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 20px;
            }
            .container {
                margin-bottom: 20px;
            }
            video {
                width: 100%;
                max-width: 400px;
            }
            svg {
                margin: 20px 0;
            }
        </style>
    </head>
    <body>
        <h1>Barcode Generator and Scanner</h1>
        
        <!-- Barcode Generator -->
        <div class="container">
            <h2>Generate Barcode</h2>
            <label for="rewardsLevel">Rewards Level:</label>
            <select id="rewardsLevel">
                <option value="1">Silver</option>
                <option value="2">Gold</option>
                <option value="3">Platinum</option>
            </select><br>
            <label for="email">Email:</label>
            <input type="email" id="email" placeholder="example@gmail.com"><br>
            <label for="issueDate">Issue Date:</label>
            <input type="date" id="issueDate"><br>
            <label for="name">Name:</label>
            <input type="text" id="name" placeholder="Your Name"><br><br>
            <button onclick="generateBarcode()">Generate Barcode</button>
            <svg id="barcode"></svg>
            <button id="downloadBarcode" onclick="downloadSVG()" style="display:none;">Download Barcode</button>
        </div>
    
        <!-- Barcode Scanner -->
        <div class="container">
            <h2>Scan Barcode</h2>
            <button onclick="startScanner()">Start Scanner</button>
            <button onclick="resetScanner()">Reset Scanner</button>
            <video id="video" autoplay muted playsinline></video>
            <div id="decodedOutput" style="margin-top: 20px;"></div>
        </div>
    
        <script>
            // Barcode Generator
            function generateBarcode() {
                const rewardsLevel = document.getElementById("rewardsLevel").value;
                const email = document.getElementById("email").value;
                const issueDate = document.getElementById("issueDate").value.replace(/-/g, '');
                const name = document.getElementById("name").value;
    
                if (!email || !issueDate || !name) {
                    alert("Please fill in all fields.");
                    return;
                }
    
                const barcodeValue = `${rewardsLevel}*${issueDate}*${email}*${name}`;
                const barcodeElement = document.getElementById("barcode");
    
                JsBarcode(barcodeElement, barcodeValue, {
                    format: "CODE128",
                    width: 2,
                    height: 100,
                    displayValue: true
                });
    
                document.getElementById("downloadBarcode").style.display = "block";
            }
    
            // Download Barcode
            function downloadSVG() {
                const svg = document.getElementById("barcode");
                const serializer = new XMLSerializer();
                const source = serializer.serializeToString(svg);
                const blob = new Blob([source], { type: "image/svg+xml;charset=utf-8" });
                const url = URL.createObjectURL(blob);
                const link = document.createElement("a");
                link.href = url;
                link.download = "barcode.svg";
                link.click();
                URL.revokeObjectURL(url);
            }
    
            // Barcode Scanner
            let codeReader;
            const videoElement = document.getElementById("video");
    
            async function startScanner() {
                if (!codeReader) {
                    codeReader = new ZXing.BrowserMultiFormatReader();
                }
                const devices = await codeReader.listVideoInputDevices();
                if (devices.length === 0) {
                    alert("No video input devices found.");
                    return;
                }
    
                const selectedDeviceId = devices[0].deviceId;
                codeReader.decodeFromVideoDevice(selectedDeviceId, videoElement, (result, error) => {
                    if (result) {
                        displayDecodedData(result.text);
                        codeReader.reset(); // Stop scanning once a code is detected
                    }
                    if (error) {
                        console.error(error);
                    }
                });
            }
    
            function displayDecodedData(data) {
                const [level, date, email, name] = data.split('*');
                const levels = { "1": "Silver", "2": "Gold", "3": "Platinum" };
                const formattedDate = new Date(date.substring(0, 4), date.substring(4, 6) - 1, date.substring(6, 8))
                    .toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });
    
                const outputDiv = document.getElementById("decodedOutput");
                outputDiv.innerHTML = `
                    <p><strong>Rewards Level:</strong> ${levels[level]}</p>
                    <p><strong>Issue Date:</strong> ${formattedDate}</p>
                    <p><strong>Email:</strong> ${email}</p>
                    <p><strong>Name:</strong> ${name}</p>
                `;
            }
    
            function resetScanner() {
                if (codeReader) {
                    codeReader.reset();
                }
                videoElement.srcObject = null;
                document.getElementById("decodedOutput").innerHTML = "";
            }
        </script>
    </body>
    </html>