摘要: 頗有意思的操做...javascript
Fundebug經受權轉載,版權歸原做者全部。html
在看到評論後,忽然意識到本身沒有提早說明,本文能夠說是一篇調研學習文,是我本身感受可行的一套方案,後續會去讀讀已經開源的一些相似的代碼庫,補足本身遺漏的一些細節,因此你們能夠看成學習文,生產環境慎用。java
若是你的應用有接入到web apm系統中,那麼你可能就知道apm系統能幫你捕獲到頁面發生的未捕獲錯誤,給出錯誤棧,幫助你定位到BUG。可是,有些時候,當你不知道用戶的具體操做時,是沒有辦法重現這個錯誤的,這時候,若是有操做錄屏,你就能夠清楚地瞭解到用戶的操做路徑,從而復現這個BUG而且修復。node
這個思路比較簡單,就是利用canvas去畫網頁內容,比較有名的庫有:html2canvas,這個庫的簡單原理是:git
這個實現是比較複雜的,可是咱們能夠直接使用,因此咱們能夠獲取到咱們想要的網頁截圖。github
爲了使得生成的視頻較爲流暢,咱們一秒中須要生成大約25幀,也就是須要25張截圖,思路流程圖以下:web
可是,這個思路有個最致命的不足:爲了視頻流暢,一秒中咱們須要25張圖,一張圖300KB,當咱們須要30秒的視頻時,圖的大小總共爲220M,這麼大的網絡開銷明顯不行。編程
爲了下降網絡開銷,咱們換個思路,咱們在最開始的頁面基礎上,記錄下一步步操做,在咱們須要"播放"的時候,按照順序應用這些操做,這樣咱們就能看到頁面的變化了。這個思路把鼠標操做和DOM變化分開:canvas
鼠標變化:小程序
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便可。
咱們在這裏只須要關心兩種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 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轉化爲Virtual DOM,其中__flow用來記錄一些參數,包括標記ID等,Virtual Node記錄了:type、attributes、children、namespace。
將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; }
在這裏,咱們使用了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; 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; }
這裏面只須要注意,當你處理新增DOM的時候,你須要一次增量的快照,這裏仍然使用Virtual DOM來記錄,在後面播放的時候,仍然生成DOM,插入到父元素便可,因此這裏須要參照DOM,也就是兄弟節點。
上面的MutationObserver並不能監控到input等元素的值變化,因此咱們須要對錶單元素的值進行特殊處理。
MDN文檔:developer.mozilla.org/en-US/docs/…
事件對象: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事件是不會冒泡的,必須使用捕獲。
MDN文檔:developer.mozilla.org/en-US/docs/…
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, }); } } }
MDN文檔:developer.mozilla.org/en-US/docs/…
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, }); } }
MDN文檔:developer.mozilla.org/en-US/docs/…
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監聽研究沒有很深刻,須要進一步深刻研究
思路比較簡單,就是從後端拿到一些信息:
利用這些信息,你就能夠首先生成頁面DOM,其中包括過濾script標籤,而後建立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在上文中省略了,這個你能夠根據本身的優化來作播放的流暢度,看是多個record做爲一幀仍是本來呈現。
Fundebug專一於JavaScript、微信小程序、微信小遊戲、支付寶小程序、React Native、Node.js和Java線上應用實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了20億+錯誤事件,付費客戶有陽光保險、核桃編程、荔枝FM、掌門1對一、微脈、青團社等衆多品牌企業。歡迎你們免費試用!