识别网页上的二维码

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

当前为 2024-01-10 提交的版本,查看 最新版本

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