Error message on Android Web Console: ReferenceError - Worker object is not defined

As someone who is new to javascript, I have been struggling to understand why popular browsers seem to handle the definition "new Worker("BarcodeWorker.js")" differently than Android WebView. The original code for this Barcode Reader is from Eddie Larsson's github repository. Thank you.

<!DOCTYPE html>
<meta charset=utf-8>
<html lang="en">
<head>
    <title>BarcodeReader</title>
</head>
<body>  
    <div id="container">
        <img width="640" height="480" src="about:blank" alt="" id="picture">
        <input id="Take-Picture" type="file" accept="image/*;capture=camera" />
        <p id="textbit"></p>
    </div>
    <script type="text/javascript">
        var takePicture = document.querySelector("#Take-Picture"),
        showPicture = document.querySelector("#picture");
        Result = document.querySelector("#textbit");
        Canvas = document.createElement("canvas");
        Canvas.width=640;
        Canvas.height=480;
        var resultArray = [];
        ctx = Canvas.getContext("2d");
        var workerCount = 0;
        function receiveMessage(e) {
            if(e.data.success === "log") {
                console.log(e.data.result);
                return;
            }
            workerCount--;
            if(e.data.success){
                var tempArray = e.data.result;
                for(var i = 0; i < tempArray.length; i++) {
                    if(resultArray.indexOf(tempArray[i]) == -1) {
                        resultArray.push(tempArray[i]);
                    }
                }
                Result.innerHTML=resultArray.join("<br />");
            }else{
                if(resultArray.length === 0 && workerCount === 0) {
                    Result.innerHTML="Decoding failed.";
                }
            }
        }
                    //Where the issue starts
        var script='';
        var DecodeWorker = new Worker("DecoderWorker.js");
        var RightWorker = new Worker("DecoderWorker.js");
        var LeftWorker = new Worker("DecoderWorker.js");
        var FlipWorker = new Worker("DecoderWorker.js");
        DecodeWorker.onmessage = receiveMessage;
        RightWorker.onmessage = receiveMessage;
        LeftWorker.onmessage = receiveMessage;
        FlipWorker.onmessage = receiveMessage;
        if(takePicture && showPicture) {
            takePicture.onchange = function (event) {
                var files = event.target.files
                if (files && files.length > 0) {
                    file = files[0];
                    try {
                        var URL = window.URL || window.webkitURL;
                        var imgURL = URL.createObjectURL(file);
                        showPicture.src = imgURL;
                        URL.revokeObjectURL(imgURL);
                        DecodeBar()
                    }
                    catch (e) {
                        try {
                            var fileReader = new FileReader();
                            fileReader.onload = function (event) {
                                showPicture.src = event.target.result;
                            };
                            fileReader.readAsDataURL(file);
                            DecodeBar()
                        }
                        catch (e) {
                            Result.innerHTML = "Neither createObjectURL or FileReader are supported";
                        }
                    }
                }
            };
        }
        function DecodeBar(){
            showPicture.onload = function(){
                ctx.drawImage(showPicture,0,0,Canvas.width,Canvas.height);
                resultArray = [];
                workerCount = 4;
                Result.innerHTML="";
                DecodeWorker.postMessage({pixels:        ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "normal"});
                RightWorker.postMessage({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "right"});
                LeftWorker.postMessage({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "left"});
                FlipWorker.postMessage({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "flip"});
            }
        }
    </script>
</body>
</html> 

Answer №1

Unfortunately, it seems that Web Workers may not be accessible to you at this time. They are not supported in current versions of Opera Mini and the Android browser (although they do work on mobile Chrome). Web Workers provide a way to offload resource-intensive tasks to another thread, preventing the main thread from becoming unresponsive and giving the appearance of freezing momentarily.

Fortunately, your code should still function without the need for Web Workers. You will simply need to integrate the JavaScript from "DecoderWorker.js" directly into your page's scope and adjust or remove the message and onmessage events by calling the functions directly from the worker.

UPDATE: I have created a functional fiddle for you to reference. In this version, I replaced instances of e.data with options and transformed the message events into functions:

/* From reader.html */

function receiveMessage(options) {
    if(options.success === "log") {
        console.log(options.result);
        return;
    }
    workerCount--;
    if(options.success){
        var tempArray = options.result;
        for(var i = 0; i < tempArray.length; i++) {
            if(resultArray.indexOf(tempArray[i]) == -1) {
                resultArray.push(tempArray[i]);
            }
        }
        Result.innerHTML=resultArray.join("<br />");
    }else{
        if(resultArray.length === 0 && workerCount === 0) {
            Result.innerHTML="Decoding failed.";
        }
    }
}
function DecodeBar(){
    showPicture.onload = function(){
        ctx.drawImage(showPicture,0,0,Canvas.width,Canvas.height);
        resultArray = [];
        workerCount = 4;
        Result.innerHTML="";
        ReadBarcode({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "normal"}, receiveMessage);
        ReadBarcode({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "right"}, receiveMessage);
        ReadBarcode({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "left"}, receiveMessage);
        ReadBarcode({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "flip"}, receiveMessage);
    }
}

/* From the last onmessage handler in DecoderWorker.js */
function  ReadBarcode(options, callback) {
        Image = {
                data: new Uint8ClampedArray(options.pixels),
                width: 640,
                height: 480
        }
        var availableFormats = ["Code128","Code93","Code39","EAN-13"];
        FormatPriority = [];
        var skipList = [];
        if(typeof options.priority != 'undefined') {
                FormatPriority = options.priority;
        }
        for(var i = 0; i < availableFormats.length; i++) {
                if(FormatPriority.indexOf(availableFormats[i]) == -1) {
                        FormatPriority.push(availableFormats[i]);
                }
        }
        if(typeof options.skip != 'undefined') {
                skipList = options.skip;
        }
        for(var i = 0; i < skipList.length; i++) {
                if(FormatPriority.indexOf(skipList[i]) != -1) {
                        FormatPriority.splice(FormatPriority.indexOf(skipList[i]),1);
                }
        }
        CreateTable();
        switch(options.cmd) {
                case "flip":
                        flipTable();
                        break;
                case "right":
                        rotateTableRight();
                        break;
                case "left":
                        rotateTableLeft();
                        break;
                case "normal":
                        break;        
        }
        var FinalResult = Main();
        if(FinalResult.length > 0) {
                callback({result: FinalResult, success: true});
        } else {
                callback({result: FinalResult, success: false});
        }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing JSON data and populating a dropdown menu with JQuery

I am facing an issue with extracting values from a JSON array using jQuery. The structure of the array is as follows: [{ "": "Select your State/Region" }, { "BAL": "Balkh" }, { "BAM": "Bamian" }] Although I have attempted to loop through the array in ord ...

Is there a way to restrict the number of checkboxes selected based on the values of radio buttons?

I am currently working with a group of radio buttons: <input type="radio" name="attending_days" value="06-18-13"/>Tuesday June 18, 2013 <input type="radio" name="attending_days" value="06-18-13"/>Wednesday June 19, 2013 <input type="radio" ...

Effectively handling server downtime with AngularJS $resource

I've implemented this code in my services.js file: angular.module('appServices', ['ngResource']). factory('User',function ($resource) { return $resource('http://localhost\\:3001/api/user/:id', { ...

What is the best way to use CSS in ReactJS to insert an image into a specific area or shape?

Currently, I'm working on developing a team picker tool specifically for Overwatch. The layout consists of cards arranged horizontally on a website, all appearing as blank gray placeholders. These cards are positioned using the JSX code snippet shown ...

Does AngularJS have a feature similar to jQuery.active?

As I utilize selenium to conduct tests on my application, I am encountering numerous ajax calls that utilize $resource or $http. It would be convenient if there was a method in angular to monitor active ajax requests so that selenium could wait until they ...

Exploring potentials in OpenLayers by filtering characteristics

Is there a way to filter map features based on their properties? For example, if I have the following property in the geojson: ... "properties": { "Start": 10 } ... How can I make it so that only features w ...

ng-include failing to retrieve file name containing UTF-8 character

I encountered an issue with the ng-include directive in the code snippet below. The file name it's trying to access contains a special character, specifically an ñ, resulting in a not found error being displayed. <div ng-include="'{{mainCtrl ...

Show values in an angular template using an array

I want to showcase values of an array using *ngFor const blockData = [ {text: sampleText1, array: [val1]}, {text: sampleText2, array: [val2, dat2]}, {text: sampleText3, array: [val3, dat3]} ] <div *ngFor="let data of blockData"> ...

"Use the data-attribute to dynamically append a child element to the

Here are a couple of divs that look like this: <div id="thisisme" data-order="1"> <div id="thisisme" data-order="2"> I am looking to insert some content into the specific div with data-order = 1. The following Javascript code is what I have t ...

Instead of scrolling through the entire window, focus on scrolling within a specific HTML element

I currently have the following elements: #elementA { position: absolute; width: 200%; height: 100%; background: linear-gradient(to right, rgba(100,0,0,0.3), rgba(0,0,250,0.3)); z-index: 250; } #containerofA { position: fixed; ...

Tips for Deploying Your NuxtJS Project on a Shared Hosting Service

After creating my NuxtJS project locally, I am now facing the challenge of deploying it to a shared hosting provider like Host Gator. Since I intend to utilize the server side rendering feature of NuxtJS, I know I need to execute the following command: n ...

Stub Node - Constructor Implementation

I've been searching for a solution for quite some time with no success, I have the following code that I want to test: some_script.js var Model = require('./models') exports.tokenizeCard = function (args) { var model = new Model(&apos ...

Working with an undefined object in jQuery

Currently, I am delving into the realm of creating MVC5 web pages utilizing JQuery and Ajax. As part of an exercise, I developed the following function: <script language="javascript"> $.get("GetCustomersByJson", null, BindData); function Bi ...

Click-o-Meter: Tracking Button Presses

I’m looking to develop a button click counter that increases every time it is downloaded. I want to implement this functionality without using a database. Here's the code snippet: <?php $counterFile = 'path/to/counter.txt' ; ...

How come JSON.parse is altering the data within nested arrays?

In my journey to master Angular 2, I decided to challenge myself by creating a Connect Four game using Angular CLI back when it was still utilizing SystemJS. Now, with the switch to the new Webpack-based CLI, I am encountering a peculiar issue... The fun ...

Exploring the functionalities of AngularJS' ng-options when working with select elements

In my search through other posts, I came across this issue but couldn't find a solution. Here is the array in question: $scope.items = [ {ID: '000001', Title: 'Chicago'}, {ID: '000002', Title: 'New York' ...

What method can I use to adjust the font style when it overlays an image?

Sorry if this is a bit unclear, but I'm trying to figure out how to change only a section of my font when it overlaps with an image while scrolling. If you visit this example website, you'll see what I'm referring to: For a visual represen ...

The unusual interactions between JavaScript and QML

Encountering strange behavior with JavaScript. I am currently working on a basic example application using QT-QML and JavaScript. Within this application, I have implemented HTTP Requests triggered by a button that sends the request through JavaScript. ...

Allow the button to be clicked only when both options from the 1/3 + 1/3 radio buttons are selected

How can I ensure that the next <button> at the bottom of the HTML is only clickable when at least one of each <input type="radio"> is checked? Also, how do I integrate this with my current function? The button itself triggers a jQuery function ...

How to save array data to a text file using node.js

I have an array containing values that I want to write to a text file using the following code. while(filedataarr.length>0) { firstelement = filedataarr.shift(); //console.log(firstelement); fs.appendFile("D:\\Temp& ...