Read QR code from Javascript and Webcam

Problem

Here, at Flockin we needed a way to login from Browser using a QR-code card and the Webcam.

For the time being (ealy 2012), Javascript have no API to stream/parse from webcam, also the main free library for QR code, Google’s ZXing (actually the only one working I know of) does not support Javascript.

Solution

The most viable solution detected was to parse Webcam from ZXing’s ActionScript module, in a very dry package that could interact with JavaScript through ExternalInterface with Javascript registering a callback.

Use

The use is pretty simple. When the swf object gets completely loaded on the page just register the JS callback which is a function that takes 1 param (String or null), the Interval of call (default 500), and an error callback (default null)

You can download all files from github, that is the project home. *Recommend you adapt the .as3 and recompile to fit your specific needs

CODE

The example below is the same found at the project’s example/index.html

// sample of function that may be registered as Callback.
function actQR( msg ){
	// msg comes null if no code were detected
	if( msg === null ){ //expect a lot of nulls
		console.log("no QR were read at this time")
	} else {
		// a valid QR reading, do something with it
		console.log(msg)
		// ask flash to stop parsing, this saves processing as webcam reading stop
		QR.stop()
	}
}

// sampe of function to be called when something goes wrong
function noWebcam( msg ){
	alert("Err! "+msg)
}

// this setInterval is a safe measure, so we don't call flash function before it is loaded;
var registerQRCb = setInterval(function(){
	//var nomeDoFlash = "QR"
	if( typeof QR === 'object' && QR != null && typeof QR.start === 'function' ){
		clearInterval(registerQRCb)
		// first param is the function signature we want the SWF to call periodicaly
		// second param is the intervall we want it, in miliseconds (default: half-second)
		// third is an signature for callback if something goes wrong, aka, user has no Webcam (default: null)
		QR.start( "actQR", 200, "noWebcam" )
	}
}, 100)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s