util.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. // 引用 https://web.tianyunperfect.cn/simple/js/util.js
  2. function lt(obj) {
  3. console.table(JSON.parse(JSON.stringify(obj)));
  4. }
  5. /**
  6. * 深度克隆
  7. * @param obj
  8. * @returns {any}
  9. */
  10. function deepClone(obj) {
  11. return JSON.parse(JSON.stringify(obj))
  12. }
  13. /**
  14. * 日期格式化 new Date().format('yyyy-MM-dd hh:mm:ss')
  15. * @param fmt
  16. * @returns {*}
  17. */
  18. Date.prototype.format = function (fmt) {
  19. const o = {
  20. "M+": this.getMonth() + 1, //月份
  21. "d+": this.getDate(), //日
  22. "h+": this.getHours(), //小时
  23. "m+": this.getMinutes(), //分
  24. "s+": this.getSeconds(), //秒
  25. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  26. "S": this.getMilliseconds() //毫秒
  27. };
  28. if (/(y+)/.test(fmt)) {
  29. fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  30. }
  31. for (const k in o) {
  32. if (new RegExp("(" + k + ")").test(fmt)) {
  33. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  34. }
  35. }
  36. return fmt;
  37. };
  38. // 添加响应拦截器
  39. axios.interceptors.response.use(function (response) {
  40. // 对响应数据做点什么
  41. return response.data;
  42. }, function (error) {
  43. // 对响应错误做点什么
  44. return Promise.reject(error);
  45. });
  46. /**
  47. * 远程请求
  48. * @type {{async: (function(*, *, *, *): Promise<unknown>), xhr_send: request.xhr_send, sync: (function(*, *, *, *): any)}}
  49. */
  50. const request = {
  51. xhr_send: function (xhr, method, headers, data) {
  52. if (headers) {
  53. for (const key in headers) {
  54. xhr.setRequestHeader(key, headers[key]);
  55. }
  56. }
  57. if (method.match(/^(POST|PUT)$/i)) {
  58. if (!headers || headers.indexOf("Content-Type") <= 0) {
  59. xhr.setRequestHeader('Content-Type', 'application/json');
  60. }
  61. xhr.send(JSON.stringify(data));
  62. } else {
  63. xhr.send();
  64. }
  65. },
  66. /**
  67. * 异步请求:request.async('https://jsonplaceholder.typicode.com/posts/1', 'GET', null, null)
  68. * .then(data => console.log(data))
  69. * .catch(error => console.error(error));
  70. */
  71. async: function (url, method, data, headers) {
  72. return new Promise((resolve, reject) => {
  73. const xhr = new XMLHttpRequest();
  74. xhr.open(method, url, true);
  75. this.xhr_send(xhr, method, headers, data);
  76. xhr.onload = () => {
  77. resolve(JSON.parse(xhr.responseText));
  78. };
  79. xhr.onerror = () => reject(xhr.statusText);
  80. });
  81. },
  82. /**
  83. * 同步请求 let a = request.sync("https://httpbin.tianyunperfect.cn/ip","GET",null,null)
  84. */
  85. sync: function (url, method, data, headers) {
  86. const xhr = new XMLHttpRequest();
  87. xhr.open(method, url, false);
  88. this.xhr_send(xhr, method, headers, data);
  89. return JSON.parse(xhr.responseText);
  90. }
  91. }
  92. /**
  93. * 休眠一段时间: await sleep(2000)
  94. * @param time
  95. * @returns {Promise<unknown>}
  96. */
  97. function sleep(time) {
  98. return new Promise((resolve) => setTimeout(resolve, time));
  99. }
  100. /**
  101. * 根据选择器 选择某一个dom,10秒钟内
  102. * @param sel
  103. * @returns {Promise<*>}
  104. */
  105. async function getDom(sel) {
  106. for (let i = 0; i < 100; i++) {
  107. let dom = document.querySelector(sel);
  108. if (dom) {
  109. return dom;
  110. } else {
  111. await sleep(100);
  112. }
  113. }
  114. }
  115. /**
  116. * 根据选择器 选择所有dom,10秒钟内
  117. * @param sel
  118. * @returns {Promise<*>}
  119. */
  120. async function getDomAll(sel) {
  121. for (let i = 0; i < 100; i++) {
  122. let dom = document.querySelectorAll(sel);
  123. if (dom.length > 0) {
  124. return dom;
  125. } else {
  126. await sleep(100);
  127. }
  128. }
  129. }
  130. /**
  131. * 添加全局样式: addGlobalStyle('.box {height: 100px !important;}');
  132. */
  133. function addGlobalStyle(newStyle) {
  134. let styleElement = document.getElementById('styles_js');
  135. if (!styleElement) {
  136. styleElement = document.createElement('style');
  137. styleElement.type = 'text/css';
  138. styleElement.id = 'styles_js';
  139. document.getElementsByTagName('head')[0].appendChild(styleElement);
  140. }
  141. styleElement.appendChild(document.createTextNode(newStyle));
  142. }
  143. /**
  144. * 获取 指定 name 的 url 参数
  145. * @param url
  146. * @param name
  147. * @returns {string|string}
  148. */
  149. function getQueryStringByUrl(url, name) {
  150. let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  151. let r = url.substring(url.indexOf('?') + 1).match(reg); //获取url中"?"符后的字符串并正则匹配
  152. let context = "";
  153. if (r != null)
  154. context = r[2];
  155. reg = null;
  156. r = null;
  157. return context == null || context === "" || context === "undefined" ? "" : decodeURI(context);
  158. }
  159. /**
  160. * 获取 指定 name 的 url 参数
  161. * @param name
  162. * @returns {string}
  163. */
  164. function getQueryString(name) {
  165. return getQueryStringByUrl(location.href, name);
  166. }
  167. const random = {
  168. /**
  169. * 获取随机数
  170. * @param min
  171. * @param max
  172. * @returns {number}
  173. */
  174. getInt: function (min, max) {
  175. min = Math.ceil(min);
  176. max = Math.floor(max);
  177. return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
  178. },
  179. /**
  180. * 获取随机的一个值
  181. * @param arr
  182. * @returns {*}
  183. */
  184. getOneFromArray: function (arr) {
  185. return arr[this.getInt(0, arr.length)];
  186. }
  187. }
  188. /**
  189. * 创建一个<eleName k="attrs[k]">text</eleName>样式的页面元素
  190. * @param eleName
  191. * @param text
  192. * @param attrs
  193. * @returns {*}
  194. */
  195. function createEle(eleName, text, attrs) {
  196. let ele = document.createElement(eleName);
  197. // innerText 也就是 <p>text会被添加到这里</p>
  198. ele.innerText = text;
  199. // attrs 的类型是一个 map
  200. for (let k in attrs) {
  201. // 遍历 attrs, 给节点 ele 添加我们想要的属性
  202. ele.setAttribute(k, attrs[k]);
  203. }
  204. // 返回节点
  205. return ele;
  206. }
  207. /**
  208. * 自动关闭提示框
  209. * @param str 提示文本
  210. * @param sec 时间(秒)
  211. */
  212. function showMsg(str, sec) {
  213. const borderColor = "#336699"; //提示窗口的边框颜色
  214. const sWidth = document.body.offsetWidth;
  215. const sHeight = document.body.offsetHeight;
  216. //背景div
  217. const bgObj = document.createElement("div");
  218. let alertBgDiv = 'alertBgDiv';
  219. bgObj.setAttribute('id', alertBgDiv);
  220. bgObj.style.cssText = `position: fixed; top: 0; background: #E8E8E8; filter: progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75; opacity: 0.6; left: 0; width: ${sWidth}px; height: ${sHeight}px; z-index: 10000`;
  221. document.body.appendChild(bgObj);
  222. //创建提示窗口的div
  223. const msgObj = document.createElement("div");
  224. let alertMsgDiv = "alertMsgDiv";
  225. msgObj.setAttribute("id", alertMsgDiv);
  226. msgObj.setAttribute("align", "center");
  227. msgObj.style.cssText = `background: white; border: 1px solid ${borderColor}; position: fixed; left: 50%; font: 15px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif; margin-left: -225px; top: ${document.body.scrollTop + (window.screen.availHeight / 2) - 150}px; text-align: center; line-height: 25px; z-index: 10001; min-width: 300px`;
  228. document.body.appendChild(msgObj);
  229. //提示信息标题
  230. const title = document.createElement("h4");
  231. let alertMsgTitle = "alertMsgTitle";
  232. title.setAttribute("id", alertMsgTitle);
  233. title.setAttribute("align", "left");
  234. title.style.cssText = `margin:0; padding:3px; background:${borderColor}; filter:progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100); opacity:0.75; border:1px solid ${borderColor}; font:12px Verdana, Geneva, Arial, Helvetica, sans-serif; color:white`;
  235. title.innerHTML = "提示信息";
  236. document.getElementById(alertMsgDiv).appendChild(title);
  237. //提示信息
  238. const txt = document.createElement("p");
  239. txt.setAttribute("id", "msgTxt");
  240. txt.style.margin = "16px 0";
  241. txt.innerHTML = str;
  242. document.getElementById(alertMsgDiv).appendChild(txt);
  243. //设置关闭时间
  244. window.setTimeout(() => {
  245. document.body.removeChild(document.getElementById(alertBgDiv));
  246. document.getElementById(alertMsgDiv).removeChild(document.getElementById(alertMsgTitle));
  247. document.body.removeChild(document.getElementById(alertMsgDiv));
  248. }, sec * 1000);
  249. }
  250. /**
  251. * 打印信息
  252. * @param obj
  253. */
  254. function log(obj) {
  255. console.table(JSON.parse(JSON.stringify(obj)));
  256. }
  257. // 添加静态资源
  258. const staticLoader = {
  259. /**
  260. * 添加js引用 : addRemoteJs("https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js");
  261. */
  262. addRemoteJs: function (jsUrl) {
  263. if (document.querySelector(`script[src="${jsUrl}"]`)) {
  264. return;
  265. }
  266. const script = document.createElement('script');
  267. script.src = jsUrl;
  268. script.type = 'text/javascript';
  269. document.head.appendChild(script);
  270. },
  271. addRemoteCss: function (cssUrl) {
  272. if (document.querySelector(`link[href="${cssUrl}"]`)) {
  273. return;
  274. }
  275. const link = document.createElement('link');
  276. link.href = cssUrl;
  277. link.rel = 'stylesheet';
  278. link.type = 'text/css';
  279. document.head.appendChild(link);
  280. },
  281. /**
  282. * 添加 Jq
  283. */
  284. addJq: function () {
  285. const jqUrl = 'https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js';
  286. this.addRemoteJs(jqUrl);
  287. }
  288. }
  289. // 复制文本工具类
  290. const copyUtil = {
  291. /**
  292. * 复制,支持复制html: copyHtml('#wish_search_list .wish_s_item');
  293. * @param css_selector
  294. * @returns {Promise<void>}
  295. */
  296. copyFromSelector: async function (css_selector) {
  297. const el = document.querySelector(css_selector);
  298. const html = el.outerHTML;
  299. await this.copyFromHtml(html);
  300. },
  301. copyFromHtml: async function (html) {
  302. try {
  303. await navigator.clipboard.write([
  304. new ClipboardItem({
  305. 'text/html': new Blob([html], {type: 'text/html'})
  306. })
  307. ]);
  308. console.log('复制成功');
  309. } catch (err) {
  310. console.error('复制失败', err);
  311. }
  312. }
  313. }
  314. /**
  315. * 在指定dom里面 添加 a 超链接 addLink(".media-title", " 转到豆瓣", `https://search.douban.com/movie/subject_search`);
  316. * @param domSelector
  317. * @param link_str
  318. * @param linkUrl
  319. */
  320. function addLink(domSelector, link_str, linkUrl) {
  321. const eleScript = document.createElement("a");
  322. eleScript.innerHTML = link_str.replaceAll(" ", "&nbsp;");
  323. eleScript.href = linkUrl;
  324. document.querySelector(domSelector).appendChild(eleScript);
  325. }