Just for recording some points casually.
Items:
- links
- Animation/Transition optimize with animationend/transitionend event.
- 特殊字符串转义、编解码
- Ajax XMLHttpRequest
- 保存网页中对象
- a 标签下载文件
- 模拟按键
links
When target="_blank", remember to add rel="noopener"
特殊字符串转义、编解码
HTMLDecode: function (text) {var temp = document.createElement("div");temp.innerHTML = text;var output = temp.innerText || temp.textContent;temp = null;return output;}
Ajax XMLHttpRequest
包括简单封装、请求头等参数
function httpRequest(config) {var xhr = new XMLHttpRequest();xhr.onload = function() {if (xhr.readyState === 4 && xhr.status === 200) {config.callback(xhr.response);}};xhr.open(config.type, config.url, true);xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');xhr.send(config.body);}
改进
const sendXMLHttpRequest = config => {const xhr = new XMLHttpRequest();xhr.open(config.method, config.url);xhr.setRequestHeader('content-type', 'application/json');xhr.onload = function() {if (xhr.status >= 200 && xhr.status < 300) {config.onSuccess(xhr.response);} else {config.onError(xhr.response);}};xhr.send(JSON.stringify(config.body));};// 用例sendXMLHttpRequest({method: 'POST',url: '/api/admin/guard',body: {url: url,},onSuccess: response => {console.log('sendToUser success: ', response);message.success('名额发放成功');},onError: response => {try {const res = JSON.parse(response);console.log('sendToUser failed: ', res);message.error(`名额发放失败:${res.message || res.err}`);} catch (e) {console.log(e);}},});
奇怪的 header
X-Request: JSON
X-Requested-With: XMLHttpRequest
保存网页中对象
参考 Snippets 中 SaveObjInPage
fileName = 'c.json';x = app.page.pins;x = JSON.stringify(x, null, 2);var blob = new Blob([x], {type: 'text/json'}),e = document.createEvent('MouseEvents'),a = document.createElement('a');a.download = fileName;a.href = window.URL.createObjectURL(blob);a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);a.dispatchEvent(e);
a 标签下载文件
function download(href, filename = '') {const a = document.createElement('a');a.download = filename;a.href = href;document.body.appendChild(a);a.click();a.remove();}// 考虑跨域, 兼容性升级版function downloadFile(url, fileName) {var x = new XMLHttpRequest();x.open('GET', url, true);x.responseType = 'blob';x.onload = function (e) {var blobUrl = window.URL.createObjectURL(x.response);download(blobUrl, fileName)window.URL.revokeObjectURL(blobUrl);};x.send();}
模拟按键
let mockKeyboardEvent = new KeyboardEvent('keydown', { ctrlKey: true });if (darkMode) {document.dispatchEvent(mockKeyboardEvent);document.dispatchEvent(mockKeyboardEvent);document.dispatchEvent(mockKeyboardEvent);}
