kang / QrCode Reader

// ==UserScript==
// @name         QrCode Reader
// @namespace    http://tampermonkey.net/
// @version      0.9
// @description  Reader QrCode via Double click Image
// @author       kyf0722@gmail.com
// @require   https://webqr.com/llqrcode.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/upng-js/2.1.0/UPNG.min.js
// @require      https://code.jquery.com/jquery-3.5.1.min.js
// @match        http*://*/*
// @grant        GM_setClipboard
// @grant        GM.xmlHttpRequest
// @license MIT
// @copyright 2020, kang (https://openuserjs.org/users/kang)
// @updateURL https://openuserjs.org/meta/kang/QrCode_Reader.meta.js
// @downloadURL https://openuserjs.org/install/kang/QrCode_Reader.user.js
// @copyright 2020, kang (https://openuserjs.org/users/kang)
// ==/UserScript==

(function () {
  'use strict';
  

  var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;
  var regex = new RegExp(expression);

  function copyToClipboard(text) {
    GM_setClipboard(text);
  }

  var jQuery = $.noConflict(true);
  console.log("start ...");

  var onImgLoad = function (selector, callback) {
    jQuery(selector).each(function () {
      if (this.complete || /*for IE 10-*/ jQuery(this).height() > 0) {
        callback.apply(this);
      }
      else {
        jQuery(this).on('load', function () {
          callback.apply(this);
        });
      }
    });
  };

  var getAbsoluteUrl = (function () {
    var a;

    return function (url) {
      if (!a) a = document.createElement('a');
      a.href = url;

      return a.href;
    };
  })();

  function toDataURL(url, callback) {
    GM.xmlHttpRequest({
      binary: true,
      url: getAbsoluteUrl(url),
      method: "GET",
      responseType: 'blob',
      onload: function (res) {
        var fr = new FileReader();
        fr.onload = function () {
          callback(this.result);
        };

        fr.readAsDataURL(res.response); // async call

      },
      onerror: function (e) {
        console.log(e)
      },
    });
  }

  function reg() {
    jQuery(this).unbind("dblclick")
    jQuery(this).dblclick(function () {
      var src = jQuery(this).attr("src");
      console.log("get img from : " + src);
      qrcode.callback = function (data) {
        console.log(data)
        if (data.match(regex)) {
          window.open(data)
        }
        else {
          copyToClipboard(data);
        }
      }
      toDataURL(src, function (d) {
        qrcode.decode(d)
      });

    });
  }
  onImgLoad("img", reg);
  setInterval(function () {
    onImgLoad("img", reg)
  }, 2500)

})();