GMLibrary

GMLibary

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/456410/1131251/GMLibrary.js

  1. // ==UserScript==
  2. // @name GMLibrary
  3. // @namespace https://greasyfork.org/users/28298
  4. // @version 1.6
  5. // @description GMLibary
  6. // @author Jerry
  7. // @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
  8. // @grant GM_setClipboard
  9. // @grant GM_download
  10. // @grant GM_addStyle
  11. // @grant GM_notification
  12. // @grant GM_xmlhttpRequest
  13. // @noframes
  14. // @license GNU GPLv3
  15. // ==/UserScript==
  16.  
  17.  
  18. // match violentmonkey supports * anywhere in url
  19. // GM_notification requires macOS to turn on notification for browser
  20. // https://violentmonkey.github.io/api/gm/
  21. // https://www.tampermonkey.net/documentation.php?ext=dhdg
  22.  
  23. /**
  24. * Finds all elements in the entire page matching `selector`, even if they are in shadowRoots.
  25. * Just like `querySelectorAll`, but automatically expand on all child `shadowRoot` elements.
  26. * @see https://stackoverflow.com/a/71692555/2228771
  27. */
  28. function querySelectorAllShadows(selector, el = document.body) {
  29. // recurse on childShadows
  30. const childShadows = Array.from(el.querySelectorAll('*')).
  31. map(el => el.shadowRoot).filter(Boolean);
  32.  
  33. // console.log('[querySelectorAllShadows]', selector, el, `(${childShadows.length} shadowRoots)`);
  34.  
  35. const childResults = childShadows.map(child => querySelectorAllShadows(selector, child));
  36. // fuse all results into singular, flat array
  37. const result = Array.from(el.querySelectorAll(selector));
  38. return result.concat(childResults).flat();
  39. }
  40.  
  41. function findx(xpath) {
  42. // e.g., findx('//select[@title="Results Per Page"]')
  43. // returns null if not found
  44. return document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null).iterateNext();
  45. }
  46.  
  47. function triggerevent(element,event) {
  48. // e.g., triggerevent (page,'change')
  49. let changeEvent = new Event(event);
  50. element.dispatchEvent(changeEvent);
  51. }
  52.  
  53. function addbutton(text,func,top,left,width,height) {
  54. //top, left, [width[, height]] in px
  55. // e.g., width 100px, height 25px
  56. // https://stackoverflow.com/a/1535421/2292993
  57. if (window.top != window.self) {
  58. return;
  59. } //don't run on frames or iframes
  60.  
  61. let btn = document.createElement("button");
  62. btn.innerHTML = text;
  63. document.body.appendChild(btn);
  64. btn.addEventListener("click", func);
  65.  
  66. btn.style.cssText = "border-radius: 5px; border:1px solid black; background-color:#D3D3D3; color:black";
  67. btn.style.position = 'absolute';
  68. btn.style.top = top+'px';
  69. btn.style.left = left+'px';
  70. if (width !== undefined) {btn.style.width = width+'px';}
  71. if (height !== undefined) {btn.style.height = height+'px';}
  72. console.log("top: " + top + 'px' + " left: " + left + 'px');
  73. }
  74.  
  75. // must call with await in async function; otherwise not working
  76. function asleep(ms) {
  77. // setTimeout(()=>{console.log("Sleeping...");},3000);
  78. console.log("Sleeping " + ms)
  79. return new Promise(resolve => setTimeout(resolve, ms));
  80. }
  81.  
  82. function sleep(millis) {
  83. var date = new Date();
  84. var curDate = null;
  85. do { curDate = new Date(); }
  86. while(curDate-date < millis);
  87. }
  88.  
  89. function hget (url) {
  90. // https://wiki.greasespot.net/GM.xmlHttpRequest
  91. // https://stackoverflow.com/a/65561572/2292993
  92. return new Promise((resolve, reject) => {
  93. GM_xmlhttpRequest({
  94. method: "GET",
  95. url: url,
  96. // headers: {
  97. // "User-Agent": "Mozilla/5.0", // If not specified, navigator.userAgent will be used.
  98. // "Accept": "text/html" // If not specified, browser defaults will be used.
  99. // },
  100. onload: function(response) {
  101. var responseXML = null;
  102. if (!response.responseXML) {
  103. responseXML = new DOMParser()
  104. .parseFromString(response.responseText, "text/html");
  105. } else {
  106. responseXML = response.responseXML;
  107. }
  108. resolve(responseXML);
  109. // console.log([
  110. // response.status,
  111. // response.statusText,
  112. // response.readyState,
  113. // response.responseHeaders,
  114. // response.responseText,
  115. // response.finalUrl,
  116. // responseXML
  117. // ].join("\n"));
  118. },
  119. onerror: function(error) {
  120. reject(error);
  121. }
  122. });
  123. });
  124. }
  125.  
  126.  
  127. // https://github.com/zevero/simpleWebstorage
  128. /*
  129. Wonder how this works?
  130. Storage is the Prototype of both localStorage and sessionStorage.
  131. Got it?
  132.  
  133. localStorage.set('myKey',{a:[1,2,5], b: 'ok'}); //can set a json Object
  134. localStorage.assign('myKey',{a:[6], c:42}); //shallow merge using Object.assign
  135. localStorage.has('myKey'); // --> true
  136. localStorage.get('myKey'); // --> {a:[6], b: 'ok', c:42}
  137. localStorage.keys(); // --> ['myKey']
  138. localStorage.remove('myKey'); // -
  139.  
  140. native:
  141. localStorage.clear();
  142. localStorage.length;
  143. */
  144. Storage.prototype.set = function(key, obj) {
  145. var t = typeof obj;
  146. if (t==='undefined' || obj===null ) this.removeItem(key);
  147. this.setItem(key, (t==='object')?JSON.stringify(obj):obj);
  148. return obj;
  149. };
  150. Storage.prototype.get = function(key) {
  151. var obj = this.getItem(key);
  152. try {
  153. var j = JSON.parse(obj);
  154. if (j && typeof j === "object") return j;
  155. } catch (e) { }
  156. return obj;
  157. };
  158. Storage.prototype.assign = function(key, obj_merge) {
  159. var obj = this.get(key);
  160. if (typeof obj !== "object" || typeof obj_merge !== "object") return null;
  161. Object.assign(obj, obj_merge);
  162. return this.set(key,obj);
  163. };
  164.  
  165. Storage.prototype.has = Storage.prototype.hasOwnProperty;
  166. Storage.prototype.remove = Storage.prototype.removeItem;
  167.  
  168. Storage.prototype.keys = function() {
  169. return Object.keys(this.valueOf());
  170. };
  171.  
  172.  
  173. /* mousetrap v1.6.5 craig.is/killing/mice */
  174. /*
  175. https://github.com/ccampbell/mousetrap
  176. By default all keyboard events will not fire if you are inside of a textarea, input, or select to prevent undesirable things from happening.
  177. If you want them to fire you can add the class mousetrap to the element. <textarea name="message" class="mousetrap"></textarea>
  178.  
  179. Supported Keys
  180. For modifier keys you can use shift, ctrl, alt, or meta.
  181. You can substitute option for alt and command for meta.
  182. Other special keys are backspace, tab, enter, return, capslock, esc, escape, space, pageup, pagedown, end, home, left, up, right, down, ins, del, and plus.
  183. Any other key you should be able to reference by name like a, /, $, *, or =.
  184.  
  185. Mousetrap.bind('esc', function() { console.log('escape'); }, 'keyup');
  186. There is a third argument you can use to specify the type of event to listen for. It can be keypress, keydown or keyup.
  187. It is recommended that you leave this argument out if you are unsure. Mousetrap will look at the keys you are binding and determine whether it should default to keypress or keydown.
  188.  
  189. Mousetrap.bind(['command+k', 'ctrl+k'], function() {
  190. console.log('command k or control k');
  191.  
  192. // return false to prevent default browser behavior
  193. // and stop event from bubbling
  194. return false;
  195. });
  196.  
  197. Mousetrap.unbind
  198. Mousetrap.trigger
  199. Mousetrap.stopCallback
  200. Mousetrap.reset
  201. Mousetrap.handleKey
  202. Mousetrap.addKeycodes
  203. */
  204. (function(q,u,c){function v(a,b,g){a.addEventListener?a.addEventListener(b,g,!1):a.attachEvent("on"+b,g)}function z(a){if("keypress"==a.type){var b=String.fromCharCode(a.which);a.shiftKey||(b=b.toLowerCase());return b}return n[a.which]?n[a.which]:r[a.which]?r[a.which]:String.fromCharCode(a.which).toLowerCase()}function F(a){var b=[];a.shiftKey&&b.push("shift");a.altKey&&b.push("alt");a.ctrlKey&&b.push("ctrl");a.metaKey&&b.push("meta");return b}function w(a){return"shift"==a||"ctrl"==a||"alt"==a||
  205. "meta"==a}function A(a,b){var g,d=[];var e=a;"+"===e?e=["+"]:(e=e.replace(/\+{2}/g,"+plus"),e=e.split("+"));for(g=0;g<e.length;++g){var m=e[g];B[m]&&(m=B[m]);b&&"keypress"!=b&&C[m]&&(m=C[m],d.push("shift"));w(m)&&d.push(m)}e=m;g=b;if(!g){if(!p){p={};for(var c in n)95<c&&112>c||n.hasOwnProperty(c)&&(p[n[c]]=c)}g=p[e]?"keydown":"keypress"}"keypress"==g&&d.length&&(g="keydown");return{key:m,modifiers:d,action:g}}function D(a,b){return null===a||a===u?!1:a===b?!0:D(a.parentNode,b)}function d(a){function b(a){a=
  206. a||{};var b=!1,l;for(l in p)a[l]?b=!0:p[l]=0;b||(x=!1)}function g(a,b,t,f,g,d){var l,E=[],h=t.type;if(!k._callbacks[a])return[];"keyup"==h&&w(a)&&(b=[a]);for(l=0;l<k._callbacks[a].length;++l){var c=k._callbacks[a][l];if((f||!c.seq||p[c.seq]==c.level)&&h==c.action){var e;(e="keypress"==h&&!t.metaKey&&!t.ctrlKey)||(e=c.modifiers,e=b.sort().join(",")===e.sort().join(","));e&&(e=f&&c.seq==f&&c.level==d,(!f&&c.combo==g||e)&&k._callbacks[a].splice(l,1),E.push(c))}}return E}function c(a,b,c,f){k.stopCallback(b,
  207. b.target||b.srcElement,c,f)||!1!==a(b,c)||(b.preventDefault?b.preventDefault():b.returnValue=!1,b.stopPropagation?b.stopPropagation():b.cancelBubble=!0)}function e(a){"number"!==typeof a.which&&(a.which=a.keyCode);var b=z(a);b&&("keyup"==a.type&&y===b?y=!1:k.handleKey(b,F(a),a))}function m(a,g,t,f){function h(c){return function(){x=c;++p[a];clearTimeout(q);q=setTimeout(b,1E3)}}function l(g){c(t,g,a);"keyup"!==f&&(y=z(g));setTimeout(b,10)}for(var d=p[a]=0;d<g.length;++d){var e=d+1===g.length?l:h(f||
  208. A(g[d+1]).action);n(g[d],e,f,a,d)}}function n(a,b,c,f,d){k._directMap[a+":"+c]=b;a=a.replace(/\s+/g," ");var e=a.split(" ");1<e.length?m(a,e,b,c):(c=A(a,c),k._callbacks[c.key]=k._callbacks[c.key]||[],g(c.key,c.modifiers,{type:c.action},f,a,d),k._callbacks[c.key][f?"unshift":"push"]({callback:b,modifiers:c.modifiers,action:c.action,seq:f,level:d,combo:a}))}var k=this;a=a||u;if(!(k instanceof d))return new d(a);k.target=a;k._callbacks={};k._directMap={};var p={},q,y=!1,r=!1,x=!1;k._handleKey=function(a,
  209. d,e){var f=g(a,d,e),h;d={};var k=0,l=!1;for(h=0;h<f.length;++h)f[h].seq&&(k=Math.max(k,f[h].level));for(h=0;h<f.length;++h)f[h].seq?f[h].level==k&&(l=!0,d[f[h].seq]=1,c(f[h].callback,e,f[h].combo,f[h].seq)):l||c(f[h].callback,e,f[h].combo);f="keypress"==e.type&&r;e.type!=x||w(a)||f||b(d);r=l&&"keydown"==e.type};k._bindMultiple=function(a,b,c){for(var d=0;d<a.length;++d)n(a[d],b,c)};v(a,"keypress",e);v(a,"keydown",e);v(a,"keyup",e)}if(q){var n={8:"backspace",9:"tab",13:"enter",16:"shift",17:"ctrl",
  210. 18:"alt",20:"capslock",27:"esc",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",45:"ins",46:"del",91:"meta",93:"meta",224:"meta"},r={106:"*",107:"+",109:"-",110:".",111:"/",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},C={"~":"`","!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0",_:"-","+":"=",":":";",'"':"'","<":",",">":".","?":"/","|":"\\"},B={option:"alt",command:"meta","return":"enter",
  211. escape:"esc",plus:"+",mod:/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"meta":"ctrl"},p;for(c=1;20>c;++c)n[111+c]="f"+c;for(c=0;9>=c;++c)n[c+96]=c.toString();d.prototype.bind=function(a,b,c){a=a instanceof Array?a:[a];this._bindMultiple.call(this,a,b,c);return this};d.prototype.unbind=function(a,b){return this.bind.call(this,a,function(){},b)};d.prototype.trigger=function(a,b){if(this._directMap[a+":"+b])this._directMap[a+":"+b]({},a);return this};d.prototype.reset=function(){this._callbacks={};
  212. this._directMap={};return this};d.prototype.stopCallback=function(a,b){if(-1<(" "+b.className+" ").indexOf(" mousetrap ")||D(b,this.target))return!1;if("composedPath"in a&&"function"===typeof a.composedPath){var c=a.composedPath()[0];c!==a.target&&(b=c)}return"INPUT"==b.tagName||"SELECT"==b.tagName||"TEXTAREA"==b.tagName||b.isContentEditable};d.prototype.handleKey=function(){return this._handleKey.apply(this,arguments)};d.addKeycodes=function(a){for(var b in a)a.hasOwnProperty(b)&&(n[b]=a[b]);p=null};
  213. d.init=function(){var a=d(u),b;for(b in a)"_"!==b.charAt(0)&&(d[b]=function(b){return function(){return a[b].apply(a,arguments)}}(b))};d.init();q.Mousetrap=d;"undefined"!==typeof module&&module.exports&&(module.exports=d);"function"===typeof define&&define.amd&&define(function(){return d})}})("undefined"!==typeof window?window:null,"undefined"!==typeof window?document:null);