识别网页上的二维码

悬浮在图片上时,右键菜单里给出识别二维码的选项。

当前为 2024-02-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name 识别网页上的二维码
  3. // @name:en Recognizing QR codes on web pages
  4. // @namespace http://tampermonkey.net/
  5. // @version 0.2.2
  6. // @description 悬浮在图片上时,右键菜单里给出识别二维码的选项。
  7. // @description:en When hovering over an image, the right-click menu gives the option to recognize the QR code.
  8. // @author aspen138
  9. // @match *://*/*
  10. // @grant GM_registerMenuCommand
  11. // @grant GM_unregisterMenuCommand
  12. // @grant GM_notification
  13. // @require https://unpkg.com/jsqr/dist/jsQR.js
  14. // @license MIT
  15. // ==/UserScript==
  16.  
  17. (function() {
  18. 'use strict';
  19.  
  20. let selectedImage = null;
  21.  
  22. // 添加右键菜单选项
  23. document.addEventListener('contextmenu', function(event) {
  24. // 确定是否是图片元素
  25. if (event.target.tagName === 'IMG') {
  26. selectedImage = event.target; // 保存当前选中的图片
  27. } else {
  28. selectedImage = null;
  29. }
  30. }, false);
  31.  
  32. // 注册菜单命令
  33. GM_registerMenuCommand("识别二维码", function() {
  34. console.log("selectedImage=", selectedImage);
  35. if (selectedImage) {
  36. decodeQRCode(selectedImage);
  37. }
  38. }, 'r');
  39.  
  40. function decodeQRCode(image) {
  41. // 创建Canvas来读取图片内容
  42. const canvas = document.createElement('canvas');
  43. const context = canvas.getContext('2d');
  44. canvas.width = image.naturalWidth; // 使用图片的原始尺寸
  45. canvas.height = image.naturalHeight;
  46. context.drawImage(image, 0, 0, canvas.width, canvas.height);
  47. const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
  48.  
  49. // 使用jsQR库识别二维码
  50. const code = jsQR(imageData.data, imageData.width, imageData.height);
  51.  
  52. // 如果识别出二维码,发送通知显示结果
  53. if (code) {
  54. alert(`二维码内容:${code.data}`+ ' 二维码识别结果'); //别用GM_notification了吧
  55. } else {
  56. alert('未识别到二维码,请确保图片中包含一个可识别的二维码。' + ' 二维码识别错误'); //别用GM_notification了吧
  57. }
  58. }
  59. })();