我的鼠标手势

一个简单的鼠标手势脚本

  1. // ==UserScript==
  2. // @name My Mouse Gestures
  3. // @name:zh-CN 我的鼠标手势
  4. // @name:zh-TW 我的滑鼠手勢
  5. // @description A simple mouse gesture script
  6. // @description:zh-CN 一个简单的鼠标手势脚本
  7. // @description:zh-TW 一個簡單的滑鼠手勢腳本
  8. // @version 0.2.2
  9. // @match *://*/*
  10. // @run-at document-start
  11. // @grant GM_openInTab
  12. // @grant window.close
  13. // @grant GM_setValue
  14. // @grant GM_getValue
  15. // @namespace https://greasyfork.org/users/4968
  16. // ==/UserScript==
  17.  
  18. // --- Settings ---
  19.  
  20. const SENSITIVITY = 3; // 1 ~ 5
  21. const TOLERANCE = 3; // 1 ~ 5
  22.  
  23. const funcs = {
  24. 'U': () => window.scrollTo(0, 0),
  25. 'D': () => window.scrollTo(0, 1073741824),
  26. 'L': () => window.history.back(),
  27. 'R': () => window.history.forward(),
  28. 'DR': () => window.top.close(),
  29. 'UD': () => window.location.reload(),
  30. 'RU': () => {
  31. GM_openInTab('about:newtab', false);
  32. if (navigator.userAgent.indexOf('Firefox') !== -1) {
  33. GM_openInTab('about:blank', false);
  34. }
  35. },
  36. 'RL': () => {
  37. let closedTabs = GM_getValue("closedTabs", []);
  38. if (closedTabs.length > 0) {
  39. let lastclosedTab = closedTabs.pop();
  40. GM_setValue("closedTabs", closedTabs);
  41. GM_openInTab(lastclosedTab, false);
  42. }
  43. }
  44. };
  45.  
  46. // ----------------
  47.  
  48. const s = 1 << ((7 - SENSITIVITY) << 1);
  49. const t1 = Math.tan(0.15708 * TOLERANCE);
  50. const t2 = 1 / t1;
  51. const abs = Math.abs;
  52.  
  53. let x, y, path, lastGesture;
  54.  
  55. const tracer = function (e) {
  56. const { clientX: cx, clientY: cy } = e;
  57. const dx = cx - x;
  58. const dy = cy - y;
  59. const distance = dx ** 2 + dy ** 2;
  60.  
  61. if (distance > s) {
  62. const slope = abs(dy / dx);
  63. let direction = '';
  64.  
  65. if (slope > t1) {
  66. direction = dy > 0 ? 'D' : 'U';
  67. } else if (slope <= t2) {
  68. direction = dx > 0 ? 'R' : 'L';
  69. }
  70.  
  71. if (lastGesture !== direction) {
  72. lastGesture = direction;
  73. path += direction;
  74. }
  75.  
  76. x = cx;
  77. y = cy;
  78. }
  79. };
  80.  
  81. window.addEventListener('mousedown', function (e) {
  82. if (e.button === 2) {
  83. x = e.clientX;
  84. y = e.clientY;
  85. path = "";
  86. lastGesture = "";
  87. window.addEventListener('mousemove', tracer, false);
  88. }
  89. }, false);
  90.  
  91. window.addEventListener('contextmenu', function (e) {
  92. window.removeEventListener('mousemove', tracer, false);
  93. if (path !== "") {
  94. e.preventDefault();
  95. if (funcs.hasOwnProperty(path)) {
  96. funcs[path]();
  97. }
  98. }
  99. }, false);
  100.  
  101. window.addEventListener("beforeunload", () => {
  102. let closedTabs = GM_getValue("closedTabs", []).slice(-10);
  103. closedTabs.push(window.location.href);
  104. GM_setValue("closedTabs", closedTabs);
  105. });