Get Text or Data from Magnetic Stripe Reader Using JavaScript and jQuery

Below is the code I came up with to redirect to a page of my liking with a query “?” variable of badgenumber when a user swipes their badge with the web page open.

The code below will work as long as the web browser or page is selected. So, if you click on something outside of the web browser, it won’t work until you put your mouse focus back in the browser.

Adjust the ‘doneTypingInterval’ to suit your needs. 1 second worked fo my purpose since it doesn’t take long to swipe a badge in a magnetic stripe reader. Also, you might notice that my output is using the ‘parseInt’ function but you could remove that and output fullText to get letters and numbers.

If you have any question, feel free to leave a comment below.

Enjoy!

  //setup before functions
  var typingTimer;                //timer identifier
  var doneTypingInterval = 1000;  //time in ms (1 second)
  var typedText = "";

  jQuery(document).keydown(function(e) {
      var keycode = event.keyCode;
      if( keycode === 59 ) {
          // don't add semicolons ; to the text
          return false;
      }
      if( keycode === 13 ) {
          return false;
          // don't add question marks ? to the text
      }
      typedText += String.fromCharCode(keycode);
  });

  //on keyup, start the countdown
  jQuery(document).keyup(function(){
      clearTimeout(typingTimer);
      if(typedText) {
          typingTimer = setTimeout(doneTyping, doneTypingInterval);
      }
  });

  //user is "finished typing," do something
  function doneTyping () {
      //do something
      var fullText = typedText.replace('¿','');
      jQuery("body").append( parseInt(fullText) );
      console.log(parseInt(fullText));
      typedText = "";
      window.location.href = 'https://dev.mattmoore.ninja?badgenumber=' + fullText
  }

Leave a Comment