Can I open the URL automaticly when I scan with WebQR - javascript

I am a programmer and I just made a simple webapp, with webview in Android studio. I have everything working except one thing. I used the WebQR set from LazarSoft. In my webapp part I have a file called webqr.js (found beneath) with the following content.
What I am trying to do is when a QR-code is scanned I want to open the result (if it is an URL) automatic in the same browser window. Now it just shows only the result.
Any help would be much appreciated.
var gCtx = null;
var gCanvas = null;
var c=0;
var stype=0;
var gUM=false;
var webkit=false;
var moz=false;
var v=null;
var imghtml='<div id="qrfile"><canvas id="out-canvas" width="320" height="240"></canvas>'+
'<div id="imghelp">drag and drop a QRCode here'+
'<br>or select a file'+
'<input type="file" onchange="handleFiles(this.files)"/>'+
'</div>'+
'</div>';
var vidhtml = '<video id="v" autoplay></video>';
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
if(files.length>0)
{
handleFiles(files);
}
else
if(dt.getData('URL'))
{
qrcode.decode(dt.getData('URL'));
}
}
function handleFiles(f)
{
var o=[];
for(var i =0;i<f.length;i++)
{
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
gCtx.clearRect(0, 0, gCanvas.width, gCanvas.height);
qrcode.decode(e.target.result);
};
})(f[i]);
reader.readAsDataURL(f[i]);
}
}
function initCanvas(w,h)
{
gCanvas = document.getElementById("qr-canvas");
gCanvas.style.width = w + "px";
gCanvas.style.height = h + "px";
gCanvas.width = w;
gCanvas.height = h;
gCtx = gCanvas.getContext("2d");
gCtx.clearRect(0, 0, w, h);
}
function captureToCanvas() {
if(stype!=1)
return;
if(gUM)
{
try{
gCtx.drawImage(v,0,0);
try{
qrcode.decode();
}
catch(e){
console.log(e);
setTimeout(captureToCanvas, 500);
};
}
catch(e){
console.log(e);
setTimeout(captureToCanvas, 500);
};
}
}
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function read(a)
{
var html="<br>";
if(a.indexOf("http://") === 0 || a.indexOf("https://") === 0)
html+="<a target='_blank' href='"+a+"'>"+a+"</a><br>";
html+="<b>"+htmlEntities(a)+"</b><br><br>";
document.getElementById("result").innerHTML=html;
}
function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
function success(stream) {
if(webkit)
v.src = window.webkitURL.createObjectURL(stream);
else
if(moz)
{
v.mozSrcObject = stream;
v.play();
}
else
v.src = stream;
gUM=true;
setTimeout(captureToCanvas, 500);
}
function error(error) {
gUM=false;
return;
}
function load()
{
if(isCanvasSupported() && window.File && window.FileReader)
{
initCanvas(800, 600);
qrcode.callback = read;
document.getElementById("mainbody").style.display="inline";
setwebcam();
}
else
{
document.getElementById("mainbody").style.display="inline";
document.getElementById("mainbody").innerHTML='<p id="mp1">QR code scanner for HTML5 capable browsers</p><br>'+
'<br><p id="mp2">sorry your browser is not supported</p><br><br>'+
'<p id="mp1">try <img src="firefox.png"/> or <img src="chrome_logo.gif"/> or <img src="Opera-logo.png"/></p>';
}
}
function setwebcam()
{
document.getElementById("result").innerHTML="- scanning -";
if(stype==1)
{
setTimeout(captureToCanvas, 500);
return;
}
var n=navigator;
document.getElementById("outdiv").innerHTML = vidhtml;
v=document.getElementById("v");
if(n.getUserMedia)
n.getUserMedia({video: true, audio: false}, success, error);
else
if(n.webkitGetUserMedia)
{
webkit=true;
n.webkitGetUserMedia({video:true, audio: false}, success, error);
}
else
if(n.mozGetUserMedia)
{
moz=true;
n.mozGetUserMedia({video: true, audio: false}, success, error);
}
//document.getElementById("qrimg").src="qrimg2.png";
//document.getElementById("webcamimg").src="webcam.png";
document.getElementById("qrimg").style.opacity=0.2;
document.getElementById("webcamimg").style.opacity=1.0;
stype=1;
setTimeout(captureToCanvas, 500);
}
function setimg()
{
document.getElementById("result").innerHTML="";
if(stype==2)
return;
document.getElementById("outdiv").innerHTML = imghtml;
//document.getElementById("qrimg").src="qrimg.png";
//document.getElementById("webcamimg").src="webcam2.png";
document.getElementById("qrimg").style.opacity=1.0;
document.getElementById("webcamimg").style.opacity=0.2;
var qrfile = document.getElementById("qrfile");
qrfile.addEventListener("dragenter", dragenter, false);
qrfile.addEventListener("dragover", dragover, false);
qrfile.addEventListener("drop", drop, false);
stype=2;
}

Welcome to JavaScript, may you long prosper with its many uses!
As you are new to JavaScript, you may not know its Browser API, but fear not!
What you are looking for is window.open
Its syntax is simple:
window.open("http://example.com")
So, when you get the url from you qr decoder, all you have to do is window.open the URL, and viola, the window will appear in a new tab!
Now if you want to open in the same browser window, then you want to use
window.location.replace("http://example.com")
This will redirect the same tab, instead of a new one!
To implement this in your program, take a look at this read function:
function read(a) {
// If it's a URL, open in here
if(a.indexOf("http://") === 0 || a.indexOf("https://") === 0)
window.location.replace(a)
}
Hope I could help!

Related

CEFSharp RegisterExtension not working

I had an screen scraper app that used CEFSharp that was working fine until I updated CEFSharp to the latest version. It appears that the way I was registering javascript extension functions no longer works. Here is my startup code:
[STAThread]
public static void Main()
{
try
{
CefSettings settings = new CefSettings();
settings.RegisterExtension(new CefExtension("showModalDialog", Resources.showModalDialog));
//Perform dependency check to make sure all relevant resources are in our output directory.
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
ProcessCommandLine();
var browser = new BrowserForm("https://www.google.com");
Application.Run(browser);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
If I comment out the settings.RegisterExtension line, it runs fine. It used to work. Here is the code for my extension:
(function () {
absolutePath = function (href) {
var link = document.createElement("a");
link.href = href;
return (link.protocol + "//" + link.host + link.pathname + link.search + link.hash);
}
showModalDialog = function (url, arg, opt) {
url = url || ''; //URL of a dialog
arg = arg || null; //arguments to a dialog
opt = opt || 'dialogWidth:300px;dialogHeight:200px'; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
var caller = showModalDialog.caller.toString();
var dialog = document.body.appendChild(document.createElement('dialog'));
dialog.setAttribute('style', opt.replace(/dialog/gi, ''));
dialog.innerHTML = '×<iframe id="dialog-body" name="dialog-body" src="' + absolutePath(url) + '" style="border: 0; width: 100%; height: 100%;"></iframe>';
//document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
document.getElementById('dialog-close').addEventListener('click', function (e) {
e.preventDefault();
dialog.close();
});
document.getElementById('dialog-body').addEventListener('load', function (e) {
this.style.height = this.contentWindow.document.body.scrollHeight + 'px';
this.style.width = this.contentWindow.document.body.scrollWidth + 'px';
this.contentWindow.close = function () {
dialog.close();
};
this.contentWindow.dialogArguments = arg;
this.window = this.contentWindow;
});
dialog.showModal();
//if using yield
if (caller.indexOf('yield') >= 0) {
return new Promise(function (resolve, reject) {
dialog.addEventListener('close', function () {
var returnValue = document.getElementById('dialog- body').contentWindow.returnValue;
document.body.removeChild(dialog);
resolve(returnValue);
});
});
}
//if using eval
var isNext = false;
var nextStmts = caller.split('\n').filter(function (stmt) {
if (isNext || stmt.indexOf('showModalDialog(') >= 0)
return isNext = true;
return false;
});
dialog.addEventListener('close', function () {
var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
document.body.removeChild(dialog);
//nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue));
//eval('{\n' + nextStmts.join('\n'));
});
throw 'Execution stopped until showModalDialog is closed';
};
})();
Did something change about the syntax of extensions?
https://bugs.chromium.org/p/chromium/issues/detail?id=665391
It's a Chrome thing and it doesn't look like they are going to fix it.

how to pause and resume voice recording in android using cordova media plugin

I'm using angularjs in visual studio.using cordova media plugin startRecord() and stopRecord() is working but not able to pause and resume recording.I'm not using media capture plugin as i don't have default recorder installed.
This is my code:
var audurl = '///storage/emulated/0/New/';
audurl += 'Voice_' + '.amr';
var mediaRec;
function recordAudio() {
mediaRec = new Media(audurl, onSuccess, onError);
mediaRec.startRecord();
}
function pauseAudio() {
mediaRec = new Media(audurl, onSuccess, onError);
mediaRec.pauseRecord();
}
thanks...
On my phone the method media.resumeRecord was not available, although in this soure-code it is defined. Nevertheless you can take advantage of all other methods, like startRecord and stopRecord, to rebuild a kind of resumeRecord function, as it is done in a handler below:
var myRecordHandler = function () {
// ALL RECORDED FILES ARE SAVED IN THIS ARRAY
var recordedAudioFiles = [];
// REMEMBER POSITION WHEN PLAYING IS STOPPED
var currentPosition = {index:0,shift:0};
// PAUSE-MODE
var paused = false;
// SET A SPECIFC DIRECTORY WHERE THE FILES ARE STORED INTO
// DEFAULT: ''
this.setDirectory = function(dir) {this.dir=dir;};
// SET FILENAME
// DEFAULT: recoredFilesX
this.setFilename = function(filename) {this.filename=filename;};
// SET MIME/Type of THE FILES;
// DEFAULT: mp3
this.setFileType = function(type) {this.filetype=type;};
// GET ALL RECORED FILES
this.getAllFiles = function() {return recordedAudioFiles;};
// STOP/PAUSE RECORDED FILES
var handleRecordedFileHold = function () {
for (var r = 0; r < recordedAudioFiles.length; r++) {
var recordedAudioFile = recordedAudioFiles[r];
if(recordedAudioFile.isBeingRecorded){
if(paused)recordedAudioFile.media.pause();
else recordedAudioFile.media.stop();
continue;
}
recordedAudioFile.duration = new Date().getTime() - recordedAudioFile.startTime;
// call release to free this created file so that it could get deleted for instance
recordedAudioFile.media.stopRecord();
recordedAudioFile.media.release();
recordedAudioFile.isBeingRecorded = true;
}
}
// START RECORDING
this.startAudioRecording = function() {
paused = false;
handleRecordedFileHold();
var dir = this.dir ? this.dir : '';
var filename = this.filename ? this.filename : 'recoredFiles';
var type = this.filetype ? this.filetype : 'mp3';
var src = dir + filename + (recordedAudioFiles.length + 1) + '.' + type;
var mediaRec = new Media(src,
function () {
console.log('recordAudio():Audio Success');
},
function (err) {
console.log('recordAudio():Audio Error: ' + err.code);
});
recordedAudioFiles.push({
media: mediaRec,
startTime: new Date().getTime()
});
mediaRec.startRecord();
}
// PAUSE RECORDING
this.pauseRecoredFiles = function () {
if(recordedAudioFiles.length){
paused = true;
clearTimeout(currentPosition.timeout);
handleRecordedFileHold();
var recoredMedia = recordedAudioFiles[currentPosition.index].media;
recoredMedia.getCurrentPosition(
function (position) {
currentPosition.shift = position;
},
function (e) {
console.log("Error getting pos=" + e);
}
);
}
}
// PLAY RECORD
this.playRecordedFiles = function () {
handleRecordedFileHold();
var playNextFile = function () {
var recoredMedia = recordedAudioFiles[currentPosition.index];
if (recoredMedia) {
if(paused){
recoredMedia.media.seekTo(currentPosition.shift*1000);
paused = false;
}
recoredMedia.media.play();
currentPosition.timeout = setTimeout(function () {
currentPosition.index++;
recoredMedia.media.stop();
playNextFile();
}, recoredMedia.duration ? recoredMedia.duration : 0);
}
else{
paused = false;
currentPosition.index = currentPosition.shift = 0;
}
};
playNextFile();
}
// RESET PLAY
this.stopRecordedFiles = function () {
currentPosition.index = currentPosition.shift = 0;
clearTimeout(currentPosition.timeout);
handleRecordedFileHold();
}
// REMOVE ALL RECORDED FILES
this.removeRecordedFiles = function() {
paused = false;
currentPosition.index = currentPosition.shift = 0;
clearTimeout(currentPosition.timeout);
handleRecordedFileHold();
recordedAudioFiles = [];
}
};
var handler = new myRecordHandler();
// you can use this handler in your functions like this:
function recordAudio() {
// records one track and stops former track if there is one
handler.startAudioRecording();
}
function playAudio() {
handler.playRecordedFiles();
}
function pauseAudio() {
handler.pauseRecoredFiles();
}
function resumeAudio() {
pauseAudio();
recordAudio();
}
function stopAudio() {
handler.stopRecordedFiles();
}
Although I could not test your directory/filenames, because I do not have this directory created on my phone, these methods might help you to to store your files in a specific directory as well as with certain filenames:
handler.setDirectory('__YOUR_DIR__');
handler.setFilename('__YOUR_FILENAME__');
handler.setFileType('__YOUR_FILETYPE__');

WebRTC file transfer and syntax querySelector

i never use WebRTC. so do not have any understand how their syntax look like.
i got a couple of syntax which i think it is not jquery. so anyone mind to tell me is it specific to webRTC related code.
document.querySelector('#stop-recording').onclick = function() {
this.disabled = true;
mediaRecorder.stop();
mediaRecorder.stream.stop();
document.querySelector('#pause-recording').disabled = true;
document.querySelector('#start-recording').disabled = false;
};
what is querySelector ?
i got the code from this url https://github.com/streamproc/MediaStreamRecorder/blob/master/demos/video-recorder.html
looking for bit info. thanks
You can refer following code:
var audio_context;
var recorder;
$(function () {
try {
//Audio Recording
window.AudioContext = window.AudioContext || window.webkitAudioContext;
navigator.getUserMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
window.URL = window.URL || window.webkitURL;
var recorderObject;
var VM_IDForAudio = "";
var audio_context = new AudioContext;
var localMediaStreamForAudio;
var audioStream;
//Audio-Video Recording (Firefox)
var videoFile = !!navigator.mozGetUserMedia ? 'video.gif' : 'video.webm';
var inner = document.querySelector('.inner');
var videoElement = document.getElementById('webcamVideo');
var VM_IDForAudioVideo = "";
var localMediaStreamForAudioVideo;
//Disable Live Webcam Button
$("#btnShowWebcam").prop("disabled", true);
} catch (e) {
//alert('No web audio support in this browser!');
console.log("No web audio support in this browser!");
}
//Audio Recording
$("[id$='btnAudioRecord']").click(function () {
//VM_IDForAudio = $("[id$='hdVMID']").val();
VM_IDForAudio = $("[id$='hdPRN']").val() + "_" + $("[id$='hdVMID']").val() + "_" +
patientDet.visitType + "_" + replateDateString(patientDet.visitDate);
$this = $(this);
$recorder = $this.parent();
if ($("[id$='btnAudioRecord']").val() == "Record Audio") {
if (VM_IDForAudio != "") {
$this.attr("value", "Stop Record");
navigator.getUserMedia({ audio: true }, function (stream) {
if (window.IsChrome) stream = new window.MediaStream(stream.getAudioTracks());
audioStream = stream;
recorder = window.RecordRTC(stream, {
type: 'audio'
});
recorder.startRecording();
}, function () { });
}
else {
//Select Patient
}
} else {
$this.attr("value", "Record Audio");
if (recorder)
recorder.stopRecording(function (url) {
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
base64data = reader.result;
PageMethods.SaveAudioRecording(base64data, VM_IDForAudio);
audioStream.stop();
}
});
}
});
//Audio-Video Recording
$("[id$='btnAudioVideoRecord']").click(function () {
//VM_IDForAudioVideo = $("[id$='hdVMID']").val();
VM_IDForAudioVideo = $("[id$='hdPRN']").val() + "_" + $("[id$='hdVMID']").val() + "_" +
patientDet.visitType + "_" + replateDateString(patientDet.visitDate);
$this = $(this);
if ($("[id$='btnAudioVideoRecord']").val() == "Record Aud/Vid") {
if (VM_IDForAudioVideo != "") {
$this.attr("value", "Stop Record");
captureUserMedia(function (stream) {
window.audioVideoRecorder = window.RecordRTC(stream, {
type: 'video', // don't forget this; otherwise you'll get video/webm instead of audio/ogg
canvas: {
width: 320,
height: 240
}
});
localMediaStreamForAudioVideo = stream;
$("#btnShowWebcam").prop("disabled", false);
window.audioVideoRecorder.startRecording();
});
}
else {
//Select Patient
}
} else {
$this.attr("value", "Record Aud/Vid");
$("#btnShowWebcam").prop("disabled", true);
window.audioVideoRecorder.stopRecording(function (url) {
convertStreams(audioVideoRecorder.getBlob(), videoFile, VM_IDForAudioVideo);
});
localMediaStreamForAudioVideo.stop();
}
});
and use RecordRTC javascript library.
for more go through this: http://recordrtc.org/RecordRTC.html,
for live demo: https://www.webrtc-experiment.com/RecordRTC/AudioVideo-on-Firefox.html
you should check webtorrent github repository, there is a detailed description about webRTC and how it is implemented. also check out the webtorrent official website

How mediasource readystate changes its state

After going through the online documentation, I have written the code mentioned below. Whenever it is a small sized file it works well. But with bigger files i am getting the Error: Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable. This is because the mediasource.readystate has changed to close. I am not able to figure out which statement changes readystate from close to open and then back to close. I logged the readystate value at all places. It changes to open inside the mediacallback method. What triggers this change ??
WT = (function () {
var mediaSource = new MediaSource();
function fileSelected(evt) {
var video = document.getElementById("vid");
var file = evt.target.files[0];
if (file) {
var NUM_CHUNKS = 10000, i = 0;
var chunkSize = Math.ceil(file.size / NUM_CHUNKS);
console.log(mediaSource.readyState);
video.src = window.URL.createObjectURL(mediaSource);
console.log(mediaSource.readyState);
var queue = [];
var mediaCallback = function (e) {
console.log(mediaSource.readyState);
var sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
sourceBuffer.addEventListener('updateend', function() {
console.log("update end");
if (queue.length ) {
sourceBuffer.appendBuffer(queue.shift());
}
}, false);
(function readChunk(i) {
var reader = new FileReader();
reader.onload = function(et) {
var buff = new Uint8Array(et.target.result);
if(!sourceBuffer.updating && queue.length === 0) {
sourceBuffer.appendBuffer(buff);
} else {
queue.push(buff);
}
if (i == NUM_CHUNKS - 1) {
console.log("end of stream");
mediaSource.endOfStream();
} else {
if (video.paused) {
console.log("video puased");
video.play(); // Start playing after 1st chunk is appended.
}
readChunk(++i);
}
};
var startByte = chunkSize * i;
var chunk = file.slice(startByte, startByte + chunkSize);
reader.readAsArrayBuffer(chunk);
})(i);
}
mediaSource.addEventListener('sourceopen', mediaCallback, false);
mediaSource.addEventListener('sourceended', function(e) {
console.log('ended: mediaSource readyState: ' + this.readyState);
}, false);
mediaSource.addEventListener('sourceclose', function(e) {
console.log('closed: mediaSource readyState: ' + this.readyState);
}, false);
} else {
console.log("NO FILE SELECTED");
}
}
return {
init: function() {
console.log("Onclick");
if (window.File && window.FileReader && window.FileList && window.Blob) {
$("document").ready(function(){
$("#fileToUpload").on("change", fileSelected);
});
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
}
})();
WT.init();

Android Web Console: UncaughtReferenceError: Worker is not defined

I'm pretty new about javascript. after a long search I couldn't find why but looks like popular browsers does somework about this definition new Worker("BarcodeWorker.js") as their base js support but Android WebView. Orginal code is from Eddie Larsson barcode reader on github. Thanks.
<!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>
It looks like Web Workers aren't available to you, (and aren't available in current versions of Opera Mini and the Android browser [but are in mobile Chrome!]). They're a way to put some resource-intensive tasks in another thread, so your main thread doesn't get held up (useful to prevent the app/page appearing to freeze for a moment).
Luckily, they shouldn't be necessary for your code to work. You'll need to move the javascript from "DecoderWorker.js" into the scope of your page, and rework/remove the message and onmessage events, instead calling the function(s) copied from the worker directly.
UPDATE: Here's a working fiddle to get you started. I just replaced e.data with options and changed the message events to 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});
}
}

Categories

Resources