在前面的話
在看到評論后,突然意識到自己沒有提前說明,本文可以說是一篇調(diào)研學(xué)習(xí)文,是我自己感覺可行的一套方案,后續(xù)會去讀讀已經(jīng)開源的一些類似的代碼庫,補足自己遺漏的一些細(xì)節(jié),所以大家可以當(dāng)作學(xué)習(xí)文,生產(chǎn)環(huán)境慎用。
錄屏重現(xiàn)錯誤場景
如果你的應(yīng)用有接入到web apm系統(tǒng)中,那么你可能就知道apm系統(tǒng)能幫你捕獲到頁面發(fā)生的未捕獲錯誤,給出錯誤棧,幫助你定位到BUG。但是,有些時候,當(dāng)你不知道用戶的具體操作時,是沒有辦法重現(xiàn)這個錯誤的,這時候,如果有操作錄屏,你就可以清楚地了解到用戶的操作路徑,從而復(fù)現(xiàn)這個BUG并且修復(fù)。
實現(xiàn)思路
思路一:利用Canvas截圖
這個思路比較簡單,就是利用canvas去畫網(wǎng)頁內(nèi)容,比較有名的庫有: html2canvas ,這個庫的簡單原理是:
這個實現(xiàn)是比較復(fù)雜的,但是我們可以直接使用,所以我們可以獲取到我們想要的網(wǎng)頁截圖。
為了使得生成的視頻較為流暢,我們一秒中需要生成大約25幀,也就是需要25張截圖,思路流程圖如下:
但是,這個思路有個最致命的不足:為了視頻流暢,一秒中我們需要25張圖,一張圖300KB,當(dāng)我們需要30秒的視頻時,圖的大小總共為220M,這么大的網(wǎng)絡(luò)開銷明顯不行。
思路二:記錄所有操作重現(xiàn)
為了降低網(wǎng)絡(luò)開銷,我們換個思路,我們在最開始的頁面基礎(chǔ)上,記錄下一步步操作,在我們需要"播放"的時候,按照順序應(yīng)用這些操作,這樣我們就能看到頁面的變化了。這個思路把鼠標(biāo)操作和DOM變化分開:
鼠標(biāo)變化:
DOM變化:
當(dāng)然這個說明是比較簡略的,鼠標(biāo)的記錄比較簡單,我們不展開講,主要說明一下DOM監(jiān)控的實現(xiàn)思路。
頁面首次全量快照
首先你可能會想到,要實現(xiàn)頁面全量快照,可以直接使用 outerHTML
const content = document.documentElement.outerHTML;
這樣就簡單記錄了頁面的所有DOM,你只需要首先給DOM增加標(biāo)記id,然后得到outerHTML,然后去除JS腳本。
但是,這里有個問題,使用 outerHTML
記錄的DOM會將把臨近的兩個TextNode合并為一個節(jié)點,而我們后續(xù)監(jiān)控DOM變化時會使用 MutationObserver
,此時你需要大量的處理來兼容這種TextNode的合并,不然你在還原操作的時候無法定位到操作的目標(biāo)節(jié)點。
那么,我們有辦法保持頁面DOM的原有結(jié)構(gòu)嗎?
答案是肯定的,在這里我們使用Virtual DOM來記錄DOM結(jié)構(gòu),把documentElement變成Virtual DOM,記錄下來,后面還原的時候重新生成DOM即可。
DOM轉(zhuǎn)化為Virtual DOM
我們在這里只需要關(guān)心兩種Node類型: Node.TEXT_NODE
和 Node.ELEMENT_NODE
。同時,要注意,SVG和SVG子元素的創(chuàng)建需要使用API:createElementNS,所以,我們在記錄Virtual DOM的時候,需要注意namespace的記錄,上代碼:
const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';const XML_NAMESPACES = ['xmlns', 'xmlns:svg', 'xmlns:xlink'];function createVirtualDom(element, isSVG = false) { switch (element.nodeType) { case Node.TEXT_NODE: return createVirtualText(element); case Node.ELEMENT_NODE: return createVirtualElement(element, isSVG || element.tagName.toLowerCase() === 'svg'); default: return null; }}function createVirtualText(element) { const vText = { text: element.nodeValue, type: 'VirtualText', }; if (typeof element.__flow !== 'undefined') { vText.__flow = element.__flow; } return vText;}function createVirtualElement(element, isSVG = false) { const tagName = element.tagName.toLowerCase(); const children = getNodeChildren(element, isSVG); const { attr, namespace } = getNodeAttributes(element, isSVG); const vElement = { tagName, type: 'VirtualElement', children, attributes: attr, namespace, }; if (typeof element.__flow !== 'undefined') { vElement.__flow = element.__flow; } return vElement;}function getNodeChildren(element, isSVG = false) { const childNodes = element.childNodes ? [...element.childNodes] : []; const children = []; childNodes.forEach((cnode) => { children.push(createVirtualDom(cnode, isSVG)); }); return children.filter(c => !!c);}function getNodeAttributes(element, isSVG = false) { const attributes = element.attributes ? [...element.attributes] : []; const attr = {}; let namespace; attributes.forEach(({ nodeName, nodeValue }) => { attr[nodeName] = nodeValue; if (XML_NAMESPACES.includes(nodeName)) { namespace = nodeValue; } else if (isSVG) { namespace = SVG_NAMESPACE; } }); return { attr, namespace };}
通過以上代碼,我們可以將整個documentElement轉(zhuǎn)化為Virtual DOM,其中__flow用來記錄一些參數(shù),包括標(biāo)記ID等,Virtual Node記錄了:type、attributes、children、namespace。
Virtual DOM還原為DOM
將Virtual DOM還原為DOM的時候就比較簡單了,只需要遞歸創(chuàng)建DOM即可,其中nodeFilter是為了過濾script元素,因為我們不需要JS腳本的執(zhí)行。
function createElement(vdom, nodeFilter = () => true) { let node; if (vdom.type === 'VirtualText') { node = document.createTextNode(vdom.text); } else { node = typeof vdom.namespace === 'undefined' ? document.createElement(vdom.tagName) : document.createElementNS(vdom.namespace, vdom.tagName); for (let name in vdom.attributes) { node.setAttribute(name, vdom.attributes[name]); } vdom.children.forEach((cnode) => { const childNode = createElement(cnode, nodeFilter); if (childNode && nodeFilter(childNode)) { node.appendChild(childNode); } }); } if (vdom.__flow) { node.__flow = vdom.__flow; } return node;}
DOM結(jié)構(gòu)變化監(jiān)控
在這里,我們使用了API:MutationObserver,更值得高興的是,這個API是所有瀏覽器都兼容的,所以我們可以大膽使用。
使用MutationObserver:
const options = { childList: true, // 是否觀察子節(jié)點的變動 subtree: true, // 是否觀察所有后代節(jié)點的變動 attributes: true, // 是否觀察屬性的變動 attributeOldValue: true, // 是否觀察屬性的變動的舊值 characterData: true, // 是否節(jié)點內(nèi)容或節(jié)點文本的變動 characterDataOldValue: true, // 是否節(jié)點內(nèi)容或節(jié)點文本的變動的舊值 // attributeFilter: ['class', 'src'] 不在此數(shù)組中的屬性變化時將被忽略};const observer = new MutationObserver((mutationList) => { // mutationList: array of mutation});observer.observe(document.documentElement, options);
使用起來很簡單,你只需要指定一個根節(jié)點和需要監(jiān)控的一些選項,那么當(dāng)DOM變化時,在callback函數(shù)中就會有一個mutationList,這是一個DOM的變化列表,其中mutation的結(jié)構(gòu)大概為:
{ type: 'childList', // or characterData、attributes target: <DOM>, // other params}
我們使用一個數(shù)組來存放mutation,具體的callback為:
const onMutationChange = (mutationsList) => { const getFlowId = (node) => { if (node) { // 新插入的DOM沒有標(biāo)記,所以這里需要兼容 if (!node.__flow) node.__flow = { id: uuid() }; return node.__flow.id; } }; mutationsList.forEach((mutation) => { const { target, type, attributeName } = mutation; const record = { type, target: getFlowId(target), }; switch (type) { case 'characterData': record.value = target.nodeValue; break; case 'attributes': record.attributeName = attributeName; record.attributeValue = target.getAttribute(attributeName); break; case 'childList': record.removedNodes = [...mutation.removedNodes].map(n => getFlowId(n)); record.addedNodes = [...mutation.addedNodes].map((n) => { const snapshot = this.takeSnapshot(n); return { ...snapshot, nextSibling: getFlowId(n.nextSibling), previousSibling: getFlowId(n.previousSibling) }; }); break; } this.records.push(record); });}function takeSnapshot(node, options = {}) { this.markNodes(node); const snapshot = { vdom: createVirtualDom(node), }; if (options.doctype === true) { snapshot.doctype = document.doctype.name; snapshot.clientWidth = document.body.clientWidth; snapshot.clientHeight = document.body.clientHeight; } return snapshot;}
這里面只需要注意,當(dāng)你處理新增DOM的時候,你需要一次增量的快照,這里仍然使用Virtual DOM來記錄,在后面播放的時候,仍然生成DOM,插入到父元素即可,所以這里需要參照DOM,也就是兄弟節(jié)點。
表單元素監(jiān)控
上面的MutationObserver并不能監(jiān)控到input等元素的值變化,所以我們需要對表單元素的值進(jìn)行特殊處理。
oninput事件監(jiān)聽
MDN文檔: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput
事件對象:select、input,textarea
window.addEventListener('input', this.onFormInput, true);onFormInput = (event) => { const target = event.target; if ( target && target.__flow && ['select', 'textarea', 'input'].includes(target.tagName.toLowerCase()) ) { this.records.push({ type: 'input', target: target.__flow.id, value: target.value, }); }}
在window上使用捕獲來捕獲事件,后面也是這樣處理的,這樣做的原因是我們是可能并經(jīng)常在冒泡階段阻止冒泡來實現(xiàn)一些功能,所以使用捕獲可以減少事件丟失,另外,像scroll事件是不會冒泡的,必須使用捕獲。
onchange事件監(jiān)聽
MDN文檔: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput
input事件沒法滿足type為checkbox和radio的監(jiān)控,所以需要借助onchange事件來監(jiān)控
window.addEventListener('change', this.onFormChange, true);onFormChange = (event) => { const target = event.target; if (target && target.__flow) { if ( target.tagName.toLowerCase() === 'input' && ['checkbox', 'radio'].includes(target.getAttribute('type')) ) { this.records.push({ type: 'checked', target: target.__flow.id, checked: target.checked, }); } }}
onfocus事件監(jiān)聽
MDN文檔: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onfocus
window.addEventListener('focus', this.onFormFocus, true);onFormFocus = (event) => { const target = event.target; if (target && target.__flow) { this.records.push({ type: 'focus', target: target.__flow.id, }); }}
onblur事件監(jiān)聽
MDN文檔: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onblur
window.addEventListener('blur', this.onFormBlur, true);onFormBlur = (event) => { const target = event.target; if (target && target.__flow) { this.records.push({ type: 'blur', target: target.__flow.id, }); }}
媒體元素變化監(jiān)聽
這里指audio和video,類似上面的表單元素,可以監(jiān)聽onplay、onpause事件、timeupdate、volumechange等等事件,然后存入records
Canvas畫布變化監(jiān)聽
canvas內(nèi)容變化沒有拋出事件,所以我們可以:
收集canvas元素,定時去更新實時內(nèi)容 hack一些畫畫的API,來拋出事件
canvas監(jiān)聽研究沒有很深入,需要進(jìn)一步深入研究
播放
思路比較簡單,就是從后端拿到一些信息:
利用這些信息,你就可以首先生成頁面DOM,其中包括過濾script標(biāo)簽,然后創(chuàng)建iframe,append到一個容器中,其中使用一個map來存儲DOM
function play(options = {}) { const { container, records = [], snapshot ={} } = options; const { vdom, doctype, clientHeight, clientWidth } = snapshot; this.nodeCache = {}; this.records = records; this.container = container; this.snapshot = snapshot; this.iframe = document.createElement('iframe'); const documentElement = createElement(vdom, (node) => { // 緩存DOM const flowId = node.__flow && node.__flow.id; if (flowId) { this.nodeCache[flowId] = node; } // 過濾script return !(node.nodeType === Node.ELEMENT_NODE && node.tagName.toLowerCase() === 'script'); }); this.iframe.style.width = `${clientWidth}px`; this.iframe.style.height = `${clientHeight}px`; container.appendChild(iframe); const doc = iframe.contentDocument; this.iframeDocument = doc; doc.open(); doc.write(`<!doctype ${doctype}><html><head></head><body></body></html>`); doc.close(); doc.replaceChild(documentElement, doc.documentElement); this.execRecords();}
function execRecords(preDuration = 0) { const record = this.records.shift(); let node; if (record) { setTimeout(() => { switch (record.type) { // 'childList'、'characterData'、 // 'attributes'、'input'、'checked'、 // 'focus'、'blur'、'play''pause'等事件的處理 } this.execRecords(record.duration); }, record.duration - preDuration) }}
上面的duration在上文中省略了,這個你可以根據(jù)自己的優(yōu)化來做播放的流暢度,看是多個record作為一幀還是原本呈現(xiàn)。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點
疑難解答