How to save barcodeScanner result to localStorage in cordova plugin barcodeScanner

1.3k views Asked by At

I got one tutorial from SAP that works for barcodeScanner wildabeast cordova plugin. From the tutorial it had an index.html itself for call the function. then i implant it in my app's index.html and the code is like this:

<div data-role="content" style="text-align: center">
    <h3 style="color: blue">Selamat datang.</h3>
    <button onclick="scan()">Scan QR Code</button> <!-- call function scan() from barcodescanner.js -->
    <a href="#manual" class="ui-btn">Masukkan Kode</a> 
      <div id="scan_results"></div> <!-- unknown -->
</div> <!-- /contain -->

and barcodescanner.js is like this:

document.addEventListener("deviceready", init, false);
    function init() {
    }

    function scan() {
        log("scanning");
        cordova.plugins.barcodeScanner.scan(scanSuccessCallback, scanErrorCallback);
    }

    function scanSuccessCallback(result) {
        log(JSON.stringify(result));
        /*
        alert("We got a barcode\n" +
        "Result: " + result.text + "\n" +
        "Format: " + result.format + "\n" +
        "Cancelled: " + result.cancelled);
         */
    }

    function scanErrorCallback(error) {
        alert("Scanning failed: " + JSON.stringify(error));
    }

    function encode() {
        log("encoding");
        if (device.platform == "Android") {  //Not supported on iOS
            var stringToEncode = "http://www.sap.com";
            cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, stringToEncode, encodeSuccessCallback, encodeErrorCallback);
        }
        else {
            log("Encoding is not supported on iOS.  See https://github.com/wildabeast/BarcodeScanner/issues/106");  
        }
    }

    function encodeSuccessCallback(result) {
        log(JSON.stringify(result));
    }

    function encodeErrorCallback(error) {
        alert("Encoding failed: " + JSON.stringify(error));
    }

    function log(line) {
        var results = document.getElementById("scan_results");
        results.innerHTML+= "<br>" + line;
    }

i suppose to save the scan result to LocalStorage and the result is not shown in the app. Can someone help me to do it like that? Thanks in advance!

1

There are 1 answers

2
tabrindle On

LocalStorage is really just an object that behaves like any other. Choose a property name and either use the getters and setters like:

localStorage.setItem('item1', '8383838838');

localStorage.getItem('item1');

Or simply:

localStorage.item1 = '8383838838';

Note that if you want to store an object in it you can, but you will have to stringify it first.

Not that this should be a problem with modern browsers, but before using this api, always check to see if LocalStorage exists first.