content-script.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. window.qrcodeContentScript = function () {
  2. let decode = function (imgUrl) {
  3. function loadImage(src) {
  4. return new Promise(resolve => {
  5. let image = new Image();
  6. image.setAttribute('crossOrigin', 'Anonymous');
  7. image.src = src;
  8. image.onload = function () {
  9. let width = this.naturalWidth;
  10. let height = this.naturalHeight;
  11. let canvas = document.createElement('canvas');
  12. canvas.style.cssText = 'position:absolute;top:-10000px;left:-10000px';
  13. document.body.appendChild(canvas);
  14. canvas.setAttribute('id', 'qr-canvas');
  15. canvas.height = height + 100;
  16. canvas.width = width + 100;
  17. let context = canvas.getContext('2d');
  18. context.fillStyle = 'rgb(255,255,255)';
  19. context.fillRect(0, 0, canvas.width, canvas.height);
  20. context.drawImage(image, 0, 0, width, height, 50, 50, width, height);
  21. resolve(canvas.toDataURL());
  22. };
  23. image.onerror = function () {
  24. resolve(src);
  25. };
  26. });
  27. }
  28. loadImage(imgUrl).then(dataUrl => {
  29. chrome.runtime.sendMessage({
  30. type: 'fh-dynamic-any-thing',
  31. thing: 'qr-decode',
  32. params: {
  33. uri: dataUrl || imgUrl
  34. }
  35. });
  36. });
  37. };
  38. return {decode}
  39. };