在看到評論後,突然意識到自己沒有事先說明,本文可以說是一篇研究學習文,是我自己感覺可行的一套方案,後續會去讀讀已經開源的一些類似的程式碼庫,補足自己遺漏的一些細節,所以大家可以當作學習文,生產環境慎用。
錄影畫面重現錯誤場景如果你的應用程式有接入web apm系統中,那麼你可能就知道apm系統能幫你捕捉到頁面發生的未捕獲錯誤,給出錯誤棧,幫助你定位到BUG。但是,有些時候,當你不知道用戶的具體操作時,是沒有辦法重現這個錯誤的,這時候,如果有操作錄屏,你就可以清楚地了解到用戶的操作路徑,從而復現這個BUG並且修復。
實現思路思路一:利用Canvas截圖這個想法比較簡單,就是利用canvas去畫網頁內容,比較有名的庫有:html2canvas,這個函式庫的簡單原理是:
這個實作是比較複雜的,但是我們可以直接使用,所以我們可以取得到我們想要的網頁截圖。
為了使得生成的影片較為流暢,我們一秒鐘中需要產生大約25幀,也就是需要25張截圖,思路流程圖如下:
但是,這個想法有個最致命的不足:為了影片流暢,一秒中我們需要25張圖,一張圖300KB,當我們需要30秒的影片時,圖的大小總共為220M,這麼大的網路開銷明顯不行。
思路二:記錄所有操作重現為了降低網路開銷,我們換個思路,我們在最開始的頁面基礎上,記錄下一步步驟操作,在我們需要播放的時候,按照順序應用這些操作,這樣我們就能看到頁面的變化了。這個想法把滑鼠操作和DOM變化分開:
滑鼠變化:
當然這個說明是比較簡略的,滑鼠的記錄比較簡單,我們不展開講,主要說明DOM監控的實作想法。
頁面首次全量快照首先你可能會想到,要實現頁面全量快照,可以直接使用outerHTML
const content = document.documentElement.outerHTML;
這樣就簡單記錄了頁面的所有DOM,你只需要先給DOM增加標記id,然後得到outerHTML,然後去掉JS腳本。
但是,這裡有個問題,使用outerHTML
記錄的DOM會將臨近的兩個TextNode合併為一個節點,而我們後續監控DOM變化時會使用MutationObserver
,此時你需要大量的處理來兼容這種TextNode的合併,不然你在還原操作的時候無法定位到操作的目標節點。
那麼,我們有辦法維持頁面DOM的原有結構嗎?
答案是肯定的,在這裡我們使用Virtual DOM來記錄DOM結構,把documentElement變成Virtual DOM,記錄下來,後面還原的時候重新生成DOM即可。
DOM轉換為Virtual DOM我們在這裡只需要關心兩種Node類型: Node.TEXT_NODE
和Node.ELEMENT_NODE
。同時,要注意,SVG和SVG子元素的建立需要使用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 createVirtualst ( text: element.nodeValue, type: 'VirtualText', }; if (typeof element.__flow !== 'undefined') { vText.__flow = element.__flow; } return vText;}function createVirtualElement(element, isSVG = false) { const tagName = element. 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(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轉換成Virtual DOM,其中__flow用來記錄一些參數,包括標記ID等,Virtual Node記錄了:type、attributes、children、namespace。
Virtual DOM還原為DOM將Virtual DOM還原為DOM的時候就比較簡單了,只需要遞歸創建DOM即可,其中nodeFilter是為了過濾script元素,因為我們不需要JS腳本的執行。
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結構變化監控
在這裡,我們使用了API:MutationObserver,更值得高興的是,這個API是所有瀏覽器都相容的,所以我們可以大膽使用。
使用MutationObserver:
const options = { childList: true, // 是否觀察子節點的變動subtree: true, // 是否觀察所有後代節點的變動attributes: true, // 是否觀察屬性的變動attributeOldValue: true, // 是否觀察屬性的變動的舊值characterData: true, // 是否節點內容或節點文字的變動characterDataOldValue: true, //是否節點內容或節點文字的變動的舊值// attributeFilter: ['class', 'src'] 不在此數組中的屬性變化時將被忽略};const observer = new MutationObserver((mutationList) => { / / mutationList: array of mutation});observer.observe(document.documentElement, options);
使用起來很簡單,你只需要指定一個根節點和需要監控的一些選項,那麼當DOM變化時,在callback函數中就會有一個mutationList,這是一個DOM的變化列表,其中mutation的結構大概是:
{ type: 'childList', // or characterData、attributes target: <DOM>, // other params}
我們使用一個陣列來存放mutation,具體的callback為:
const onMutationChange = (mutationsList) => { const getFlowId = (node) => { if (node) { // 新插入的DOM沒有標記,所以這裡需要相容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; ; case 'attributes': record.value = target.nodeValue; ; case 'attributes': record.attributeName 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;}
這裡面只需要注意,當你處理新增DOM的時候,你需要一次增量的快照,這裡仍然使用Virtual DOM來記錄,在後面播放的時候,仍然生成DOM,插入到父元素即可,所以這裡需要參照DOM,也就是兄弟節點。
表單元素監控上面的MutationObserver並不能監控到input等元素的值變化,所以我們需要對表單元素的值進行特殊處理。
oninput事件監聽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上使用捕獲來捕獲事件,後面也是這樣處理的,這樣做的原因是我們是可能並經常在冒泡階段阻止冒泡來實現一些功能,所以使用捕獲可以減少事件丟失,另外,像scroll事件是不會冒泡的,必須使用捕獲。
onchange事件監聽MDN文件:https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput
input事件無法滿足type為checkbox和radio的監控,所以需要使用onchange事件來監控
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事件監聽
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事件監聽
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, }); }}媒體元素變化監聽
這裡指audio和video,類似上面的表單元素,可以監聽onplay、onpause事件、timeupdate、volumechange等等事件,然後存入records
Canvas畫布變化監聽canvas內容變化沒有拋出事件,所以我們可以:
收集canvas元素,定時去更新即時內容hack一些畫的API,來拋出事件
canvas監聽研究沒有很深入,需要進一步深入研究
播放思路比較簡單,就是從後端拿到一些資訊:
利用這些訊息,你就可以先產生頁面DOM,其中包含過濾script標籤,然後建立iframe,append到一個容器中,其中使用一個map來儲存DOM
function play(options = {}) { const { container, records = [], snapshot ={} } = options; const { vdom, doctype, clientHeight, clientWidth } = snapshot; this.nodeCache = {}; this.records = {}; this.records = {}; this.records = {}; 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 (flowIdM 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在上文中省略了,這個你可以根據自己的優化來做播放的流暢度,看是多個record作為一幀還是原本呈現。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。