global_module

@XiaoYingYo global_module

当前为 2023-05-02 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/464780/1184275/global_module.js

  1. class global_module {
  2.  
  3. static UrlCache = {}
  4.  
  5. /**
  6. *
  7. * @param {*} selector 目标元素选择器
  8. * @param {*} iframe 可选-iframe选择器 可以是字符串选择器或者元素
  9. * @param {*} callback 可选-回调函数
  10. * @param {*} time 可选-每次查询间隔时间
  11. * @param {*} timeout 可选-超时时间
  12. * @param {*} baseElement 可选-基础元素 可以是字符串选择器或者元素
  13. * @returns
  14. */
  15. static async waitForElement(selectors, iframe = null, callback = null, time = 100, timeout = 1000 * 30, baseElement = null, index = null, isWrapped = true) {
  16. if (time == null) {
  17. time = 100;
  18. }
  19. if (timeout == null) {
  20. timeout = 1000 * 30;
  21. }
  22. if (isWrapped == null) {
  23. isWrapped = true;
  24. }
  25. return new Promise(async (resolve) => {
  26. let startTime = Date.now();
  27. let iframeElement, base, elements = [];
  28. if (typeof selectors === 'string') {
  29. selectors = [selectors];
  30. }
  31. if (iframe) {
  32. try {
  33. iframeElement = iframe.getAttribute("id");
  34. iframeElement = iframe;
  35. } catch (e) {
  36. if (typeof iframe === 'string') {
  37. iframeElement = await global_module.waitForElement(iframe);
  38. } else {
  39. iframeElement = iframe;
  40. }
  41. }
  42. if (!iframeElement) {
  43. resolve(null);
  44. return;
  45. }
  46. for (let selector of selectors) {
  47. let foundElements = isWrapped ? $(iframeElement).contents().find(selector) : iframeElement.contentDocument.querySelectorAll(selector);
  48. if (foundElements.length > 0) {
  49. elements = foundElements;
  50. break;
  51. }
  52. }
  53. } else if (baseElement) {
  54. try {
  55. base = baseElement.getAttribute("id");
  56. base = baseElement;
  57. } catch (e) {
  58. if (typeof baseElement === 'string') {
  59. base = await global_module.waitForElement(baseElement);
  60. } else {
  61. base = baseElement;
  62. }
  63. }
  64.  
  65. if (!base) {
  66. resolve(null);
  67. return;
  68. }
  69. for (let selector of selectors) {
  70. let foundElements = isWrapped ? base.find(selector) : base[0].querySelectorAll(selector);
  71. if (foundElements.length > 0) {
  72. elements = foundElements;
  73. break;
  74. }
  75. }
  76. } else {
  77. for (let selector of selectors) {
  78. let foundElements = document.querySelectorAll(selector);
  79. if (foundElements.length > 0) {
  80. elements = foundElements;
  81. break;
  82. }
  83. }
  84. }
  85.  
  86. if (index != null) {
  87. elements = elements[index];
  88. if (!elements) {
  89. resolve(null);
  90. return;
  91. }
  92. }
  93.  
  94. if (elements.length > 0) {
  95. if (isWrapped) {
  96. elements = $(elements);
  97. }
  98. if (callback) {
  99. callback(elements);
  100. }
  101. resolve(elements);
  102. } else {
  103. if (timeout !== -1 && Date.now() - startTime >= timeout) {
  104. resolve(null);
  105. return;
  106. }
  107. setTimeout(async () => {
  108. resolve(await global_module.waitForElement(selectors, iframe, callback, time, timeout, baseElement, index, isWrapped));
  109. }, time);
  110. }
  111. });
  112. }
  113.  
  114. static copyText(text) {
  115. let textarea = document.createElement("textarea");
  116. textarea.value = text;
  117. document.body.appendChild(textarea);
  118. textarea.select();
  119. document.execCommand("copy");
  120. textarea.remove();
  121. }
  122.  
  123. static stripHtmlTags(html) {
  124. return html.replace(/<[^>]+>/g, '');
  125. }
  126.  
  127. static async Ajax_Xhr(url, Way, data) {
  128. return new Promise(function (resolve) {
  129. let h = ["html", "txt", "json", "xml", "js", "css"];
  130. if (global_module.UrlCache[url] == null) {
  131. if (h.indexOf(Way) == -1) {
  132. Way = "GET";
  133. }
  134. let xhr = new XMLHttpRequest();
  135. xhr.open(Way, url, true);
  136. xhr.onreadystatechange = function () {
  137. if (xhr.readyState == 4 && xhr.status == 200) {
  138. let ret = xhr.responseText;
  139. let p = url;
  140. if (p.indexOf("?") != -1) p = p.substring(0, p.indexOf("?"));
  141. p = p.substring(p.lastIndexOf(".") + 1);
  142. if (h.indexOf(p) != -1) {
  143. global_module.UrlCache[url] = ret
  144. }
  145. resolve(ret);
  146. return ret;
  147. };
  148. }
  149. xhr.send(data);
  150. } else {
  151. resolve(global_module.UrlCache[url]);
  152. return global_module.UrlCache[url]
  153. }
  154. }).then(function (result) {
  155. return result
  156. }).catch(function (error) {
  157. console.log(error)
  158. })
  159. };
  160.  
  161. static GetUrlParm(name) {
  162. let href = window.location.href
  163. let parms = href.substring(href.indexOf("?") + 1);
  164. let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  165. let r = parms.match(reg);
  166. if (r != null) {
  167. return decodeURIComponent(r[2]);
  168. }
  169. return null;
  170. };
  171.  
  172. static SetUrlParm(href, name, value) {
  173. if (href == null || href == "") {
  174. href = location.href;
  175. };
  176. let index = href.indexOf("?");
  177. if (index == -1) {
  178. href += "?" + name + "=" + value;
  179. } else {
  180. let parms = href.substring(href.indexOf("?") + 1);
  181. let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  182. let r = parms.match(reg);
  183. if (r != null) {
  184. href = href.replace(r[0], r[0].replace(r[2], value));
  185. } else {
  186. href += "&" + name + "=" + value;
  187. }
  188. }
  189. return href;
  190. };
  191.  
  192. // 根据扩展名引入js或css
  193. static async LoadJsOrCss(url, scriptStr = "") {
  194. return new Promise(function (resolve) {
  195. if (Array.isArray(url)) {
  196. let count = 0;
  197. for (let i = 0; i < url.length; i++) {
  198. global_module.LoadJsOrCss(url[i]).then(() => {
  199. count++;
  200. if (count == url.length) {
  201. resolve();
  202. }
  203. });
  204. }
  205. return;
  206. }
  207. let p = url;
  208. let s = 0;
  209. if (p.indexOf("?") != -1) p = p.substring(0, p.indexOf("?"));
  210. p = p.substring(p.lastIndexOf(".") + 1);
  211. let t;
  212. if (p == "js") {
  213. let script = document.createElement("script");
  214. script.type = "text/javascript";
  215. script.id = url;
  216. if (scriptStr == "") {
  217. script.src = url;
  218. } else {
  219. script.innerHTML = scriptStr;
  220. s = 1;
  221. }
  222. t = script;
  223. } else if (p == "css") {
  224. if (scriptStr == "") {
  225. let link = document.createElement("link");
  226. link.href = url;
  227. link.type = "text/css";
  228. link.rel = "stylesheet";
  229. link.id = url;
  230. t = link;
  231. } else {
  232. let style = document.createElement("style");
  233. style.type = "text/css";
  234. style.id = url;
  235. style.innerHTML = scriptStr;
  236. t = style;
  237. s = 1;
  238. }
  239. };
  240. if (t != null) {
  241. t.onload = function () {
  242. resolve(t);
  243. };
  244. } else {
  245. resolve(null);
  246. };
  247. try { document.getElementsByTagName("head")[0].appendChild(t); } catch (e) { document.appendChild(t); }
  248. if (s != 0) {
  249. resolve(null);
  250. }
  251. }).then(function (r) {
  252. return r;
  253. }).catch(function (e) {
  254. console.log(e);
  255. });
  256. }
  257.  
  258. static RemoveJsOrCss(url) {
  259. $("[id='" + url + "']").remove();
  260. }
  261.  
  262. static IframeInjectScript(element, type = "js", Str) {
  263. let Dom = $(element).contents().find("body");
  264. if (type == "js") {
  265. $(element)[0].contentWindow.window.eval(Str);
  266. } else if (type == "css") {
  267. Dom.append("<style>" + Str + "</style>");
  268. }
  269. }
  270.  
  271. static async waitPageLoad() {
  272. return new Promise(function (resolve) {
  273. if (document.readyState == "complete") {
  274. resolve();
  275. } else {
  276. let S = setInterval(function () {
  277. if (document.readyState == "complete") {
  278. clearInterval(S);
  279. resolve();
  280. };
  281. }, 200);
  282. };
  283. });
  284. }
  285.  
  286. static HOOKFunction(fun, before, after) {
  287. if (typeof (fun) == "string") {
  288. return "HOOK的对象必须是函数";
  289. };
  290. let old = fun;
  291. fun = function () {
  292. if (typeof (before) == "function") {
  293. before();
  294. };
  295. let result = old.apply(this, arguments);
  296. if (typeof (after) == "function") {
  297. after();
  298. };
  299. return result;
  300. };
  301. return fun;
  302. }
  303.  
  304. static getParentFolderPath(filePath) {
  305. var pathSeparator;
  306. if (filePath.indexOf("/") !== -1) {
  307. pathSeparator = "/";
  308. } else if (filePath.indexOf("\\") !== -1) {
  309. pathSeparator = "\\";
  310. } else if (filePath.indexOf("\\\\") !== -1) {
  311. pathSeparator = "\\\\";
  312. }
  313. var parts = filePath.split(pathSeparator);
  314. parts.pop();
  315. return parts.join(pathSeparator);
  316. }
  317.  
  318. static RandomIP() {
  319. let ip = "";
  320. for (let i = 0; i < 4; i++) {
  321. ip += Math.floor(Math.random() * 255) + ".";
  322. };
  323. ip = ip.substring(0, ip.length - 1);
  324. return ip;
  325. }
  326.  
  327. static RandomIPHeader() {
  328. let ip = this.RandomIP();
  329. let header = {
  330. "X-Forwarded-For": ip,
  331. "X-Originating-IP": ip,
  332. "X-Remote-Addr": ip,
  333. "X-Remote-IP": ip,
  334. };
  335. return header;
  336. }
  337.  
  338. static MoveElement(obj, GoToX) {
  339. if (obj == null) return;
  340. if (obj.length > 0) obj = obj[0];
  341. let event = document.createEvent("MouseEvents");
  342. event.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  343. obj.dispatchEvent(event);
  344. let x = 0;
  345. let timer = setInterval(function () {
  346. x += 5;
  347. let event = document.createEvent("MouseEvents");
  348. event.initMouseEvent("mousemove", true, true, window, 0, 0, 0, x, 0, false, false, false, false, 0, null);
  349. obj.dispatchEvent(event);
  350. if (x >= GoToX) {
  351. clearInterval(timer);
  352. let event = document.createEvent("MouseEvents");
  353. event.initMouseEvent("mouseup", true, true, window, 0, 0, 0, 260, 0, false, false, false, false, 0, null);
  354. obj.dispatchEvent(event);
  355. }
  356. }, 10);
  357. }
  358.  
  359. static clickElement(element) {
  360. if (element == null) return false;
  361. let Event = document.createEvent("MouseEvents");
  362. Event.initEvent("click", true, true);
  363. element.dispatchEvent(Event);
  364. return true;
  365. }
  366.  
  367. static getLayerelement(layeri) {
  368. return $("div[id^='layui-layer" + layeri + "'][type][times='" + layeri + "']").eq(0)
  369. }
  370.  
  371. static getLayerelementIframe(layeri) {
  372. return global_module.getLayerelement(layeri).find("iframe").eq(0);
  373. }
  374.  
  375. static getLayerelementIframeBody(layeri) {
  376. return global_module.getLayerelementIframe(layeri).contents().find("body");
  377. }
  378.  
  379. static getLayerBtn(layeri, index) {
  380. return global_module.getLayerelement(layeri).find("a[class^='layui-layer-btn']").eq(index);
  381. }
  382.  
  383. static setLayerImgPath(layeri, Path) {
  384. if (Path.substr(-1) != "/" && Path.substr(-1) != "\\") { if (Path.indexOf("/") != -1) { Path += "/"; } else { Path += "\\"; } }
  385. let element = global_module.getLayerelement(layeri);
  386. let i = $(element).find("i");
  387. for (let m = 0; m < i.length; m++) {
  388. let className = $(i[m]).attr("class");
  389. if (className.indexOf("ico") == -1) {
  390. continue;
  391. }
  392. let bg = $(i[m]).css("background-image");
  393. let bgPath = bg.substring(bg.indexOf("(") + 1, bg.indexOf(")"));
  394. let fileName = bgPath.substring(bgPath.lastIndexOf("/") + 1);
  395. fileName = fileName.replace(/\"/g, "").replace(/\'/g, "");
  396. $(i[m]).css("background-image", "url(" + Path + fileName + ")");
  397. }
  398. }
  399.  
  400. static async simulateKeydown(ele, key, interval = 200) {
  401. return new Promise(function (resolve) {
  402. if (key.length == 0) {
  403. resolve();
  404. return;
  405. }
  406. if (ele == null) {
  407. resolve();
  408. return;
  409. }
  410. key = key.toLowerCase();
  411. let keys = key.split("+");
  412. let event;
  413. if (typeof (Event) === 'function') {
  414. event = new Event('keydown');
  415. } else {
  416. event = document.createEvent('Event');
  417. event.initEvent('keydown', true, true);
  418. }
  419. event.key = keys[keys.length - 1];
  420. for (let i = 0; i < keys.length - 1; i++) {
  421. event[keys[i] + "Key"] = true;
  422. }
  423. ele.dispatchEvent(event);
  424. setTimeout(() => {
  425. let event;
  426. if (typeof (Event) === 'function') {
  427. event = new Event('keyup');
  428. } else {
  429. event = document.createEvent('Event');
  430. event.initEvent('keyup', true, true);
  431. }
  432. event.key = keys[keys.length - 1];
  433. for (let i = 0; i < keys.length - 1; i++) {
  434. event[keys[i] + "Key"] = false;
  435. }
  436. ele.dispatchEvent(event);
  437. resolve();
  438. }, interval);
  439. });
  440. }
  441.  
  442. static debounce(fn, delay) {
  443. let timeoutId;
  444. let promiseResolve;
  445. let promise = new Promise(resolve => promiseResolve = resolve);
  446. return function () {
  447. if (timeoutId) {
  448. clearTimeout(timeoutId);
  449. }
  450. timeoutId = setTimeout(async () => {
  451. timeoutId = null;
  452. if (fn.constructor.name === 'AsyncFunction') {
  453. let result = await fn.apply(this, arguments);
  454. promiseResolve(result);
  455. } else {
  456. let result = fn.apply(this, arguments);
  457. promiseResolve(result);
  458. }
  459. }, delay);
  460.  
  461. return promise;
  462. };
  463. }
  464.  
  465. static observeDomChanges(ele = null, callback, MutationObserverFunction = null) {
  466. if (MutationObserverFunction == null || typeof (MutationObserverFunction) != "function") {
  467. MutationObserverFunction = MutationObserver;
  468. }
  469. const observer = new MutationObserverFunction(
  470. function (mutations) {
  471. mutations.forEach(function (mutation) {
  472. if (mutation.type === "childList" && mutation.target.getAttribute("data-inserted-append") == null) {
  473. callback(mutation.target);
  474. };
  475. });
  476. }
  477. );
  478. const options = {
  479. childList: true,
  480. subtree: true,
  481. characterData: true,
  482. attributeFilter: ["data-inserted-append"]
  483. };
  484. if (ele == null) {
  485. ele = document;
  486. }
  487. observer.observe(ele, options);
  488. }
  489.  
  490. static getRandomString(len) {
  491. len = len || 32;
  492. let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  493. let maxPos = $chars.length;
  494. let pwd = '';
  495. for (let i = 0; i < len; i++) {
  496. pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  497. }
  498. return pwd;
  499. }
  500.  
  501. static getRandomNumber(len) {
  502. let $chars = '0123456789';
  503. let maxPos = $chars.length;
  504. let pwd = '';
  505. for (let i = 0; i < len; i++) {
  506. pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  507. }
  508. return pwd;
  509. }
  510.  
  511. static hideAndCreateDom(Element) {
  512. let dom = $(Element).eq(0);
  513. $(dom).hide();
  514. let clone = $(dom).clone();
  515. $(dom).after(clone);
  516. clone.show();
  517. return clone;
  518. }
  519.  
  520. static cloneAndHide(target, InsertMethod = 0, BaseElement = null) {
  521. if (InsertMethod == null) {
  522. InsertMethod = 0;
  523. }
  524. let clone = document.createElement(target.tagName);
  525. let attributes = target.attributes;
  526. for (let i = 0; i < attributes.length; i++) {
  527. clone.setAttribute(attributes[i].name, attributes[i].value);
  528. }
  529. let childNodes = target.childNodes;
  530. for (let i = 0; i < childNodes.length; i++) {
  531. clone.appendChild(childNodes[i].cloneNode(true));
  532. }
  533. target.style.display = "none";
  534. let parent;
  535. if (BaseElement !== null) {
  536. parent = BaseElement;
  537. } else {
  538. parent = target.parentNode;
  539. }
  540. switch (InsertMethod) {
  541. case 0:
  542. parent.appendChild(clone);
  543. break;
  544. case 1:
  545. parent.insertBefore(clone, target.nextSibling);
  546. break;
  547. case 2:
  548. parent.insertBefore(clone, target);
  549. break;
  550. default:
  551. parent.appendChild(clone);
  552. }
  553. return clone;
  554. }
  555.  
  556. static async AnimateText(ele, text, Delay = 100) {
  557. return new Promise(function (resolve) {
  558. let currentText = "";
  559. let i = 0;
  560. let height = ele.parent().css("height");
  561. if (height == null) {
  562. resolve();
  563. return;
  564. }
  565. height = height.substring(0, height.length - 2) - 22 + "px";
  566. let cursor;
  567. cursor = document.createElement('span');
  568. cursor.classList.add('cursor');
  569. cursor.style.backgroundColor = "#fff";
  570. cursor.style.width = "3px";
  571. cursor.style.height = height;
  572. cursor.style.display = "inline-block";
  573. cursor.style.animation = "blink 1s step-end infinite";
  574. let interval = setInterval(() => {
  575. currentText += text[i];
  576. ele.text(currentText);
  577. ele.append(cursor);
  578. i++;
  579. if (i === text.length) {
  580. clearInterval(interval);
  581. resolve();
  582. setTimeout(() => {
  583. cursor.remove();
  584. }, 200);
  585. }
  586. }, Delay);
  587. });
  588. }
  589.  
  590. static getMiddleString(str, start, end) {
  591. return str.substring(str.indexOf(start) + 1, str.indexOf(end));
  592. }
  593.  
  594. static Cookie = {
  595. get: function (name) {
  596. let match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  597. return match && decodeURIComponent(match[2]);
  598. },
  599. set: function (name, value, days) {
  600. if (days == null) {
  601. days = 1;
  602. }
  603. let d = new Date;
  604. d.setTime(d.getTime() + 24 * 60 * 60 * 1000 * days);
  605. document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
  606. },
  607. delete: function (name) {
  608. this.set(name, '', -1);
  609. },
  610. clear: function () {
  611. for (let key in this.get()) {
  612. this.delete(key);
  613. }
  614. }
  615. }
  616.  
  617. static LocalStorage = {
  618. exportLocalStorage: function () {
  619. let localStorageData = {};
  620. for (let i = 0; i < localStorage.length; i++) {
  621. let key = localStorage.key(i);
  622. let value = localStorage.getItem(key);
  623. localStorageData[key] = value;
  624. };
  625. let jsonString = JSON.stringify(localStorageData, null, 2);
  626. return jsonString;
  627. },
  628. importLocalStorage: function (localStorageString) {
  629. let localStorageData = JSON.parse(localStorageString);
  630. for (let key in localStorageData) {
  631. localStorage.setItem(key, localStorageData[key]);
  632. };
  633. }
  634. }
  635.  
  636. static AnalogInput = {
  637. clickElement: function (el) {
  638. if (!el || el && 'function' !== typeof el.click) {
  639. return false;
  640. }
  641.  
  642. el.click();
  643. return true;
  644. },
  645. doFocusElement: function (el, setValue) {
  646. if (setValue) {
  647. let existingValue = el.value;
  648. el.focus();
  649. el.value !== existingValue && (el.value = existingValue);
  650. } else {
  651. el.focus();
  652. }
  653. },
  654. normalizeEvent: function (el, eventName) {
  655. let ev;
  656. if ('KeyboardEvent' in window) {
  657. ev = new window.KeyboardEvent(eventName, {
  658. bubbles: true,
  659. cancelable: false
  660. });
  661. } else {
  662. ev = el.ownerDocument.createEvent('Events');
  663. ev.initEvent(eventName, true, false);
  664. ev.charCode = 0;
  665. ev.keyCode = 0;
  666. ev.which = 0;
  667. ev.srcElement = el;
  668. ev.target = el;
  669. }
  670. return ev;
  671. },
  672. setValueForElement: function (el) {
  673. let valueToSet = el.value;
  674. this.clickElement(el);
  675. this.doFocusElement(el, false);
  676. el.dispatchEvent(this.normalizeEvent(el, 'keydown'));
  677. el.dispatchEvent(this.normalizeEvent(el, 'keypress'));
  678. el.dispatchEvent(this.normalizeEvent(el, 'keyup'));
  679. el.value !== valueToSet && (el.value = valueToSet);
  680. },
  681. setValueForElementByEvent: function (el) {
  682. let valueToSet = el.value, ev1 = el.ownerDocument.createEvent('HTMLEvents'), ev2 = el.ownerDocument.createEvent('HTMLEvents');
  683. el.dispatchEvent(this.normalizeEvent(el, 'keydown'));
  684. el.dispatchEvent(this.normalizeEvent(el, 'keypress'));
  685. el.dispatchEvent(this.normalizeEvent(el, 'keyup'));
  686. ev2.initEvent('input', true, true);
  687. el.dispatchEvent(ev2);
  688. ev1.initEvent('change', true, true);
  689. el.dispatchEvent(ev1);
  690. el.blur();
  691. el.value !== valueToSet && (el.value = valueToSet);
  692. },
  693. doAllFillOperations: function (el, afterValSetFunc) {
  694. this.setValueForElement(el);
  695. if (typeof (afterValSetFunc) == "function") {
  696. afterValSetFunc(el);
  697. }
  698. this.setValueForElementByEvent(el);
  699. },
  700. AnalogInput: function (el, op) {
  701. el.value == op || this.doAllFillOperations(el, function (theEl) {
  702. if (!theEl.type && theEl.tagName.toLowerCase() === 'span') {
  703. theEl.innerText = op;
  704. return;
  705. }
  706. theEl.value = op;
  707. });
  708. }
  709. }
  710. }
  711.  
  712. try {
  713. window["global_module"] = global_module;
  714. } catch (e) { }
  715. try {
  716. module.exports = global_module;
  717. } catch (e) { }