nested record iframe (#63)

* pick nested branch

* iframe snapshot

* temp: add bundle file to git

* revert ignore file

* refactor iframe impl
1. do callback one iframe is loaded, let rrweb handle the rest
2. handle iframe as normal element in rebuild

* rename hook function
This commit is contained in:
yz-yu
2021-02-07 14:00:22 +08:00
committed by GitHub
parent a3ff5e5ea8
commit 98aa732d17
11 changed files with 343 additions and 7 deletions

View File

@@ -198,13 +198,20 @@ export function buildNodeWithSN(
map: idNodeMap; map: idNodeMap;
skipChild?: boolean; skipChild?: boolean;
hackCss: boolean; hackCss: boolean;
afterAppend?: (n: INode) => unknown;
}, },
): INode | null { ): INode | null {
const { doc, map, skipChild = false, hackCss = true } = options; const { doc, map, skipChild = false, hackCss = true, afterAppend } = options;
let node = buildNode(n, { doc, hackCss }); let node = buildNode(n, { doc, hackCss });
if (!node) { if (!node) {
return null; return null;
} }
if (n.rootId) {
console.assert(
((map[n.rootId] as unknown) as Document) === doc,
'Target document should has the same root id.',
);
}
// use target document as root document // use target document as root document
if (n.type === NodeType.Document) { if (n.type === NodeType.Document) {
// close before open to make sure document was closed // close before open to make sure document was closed
@@ -215,6 +222,7 @@ export function buildNodeWithSN(
(node as INode).__sn = n; (node as INode).__sn = n;
map[n.id] = node as INode; map[n.id] = node as INode;
if ( if (
(n.type === NodeType.Document || n.type === NodeType.Element) && (n.type === NodeType.Document || n.type === NodeType.Element) &&
!skipChild !skipChild
@@ -225,14 +233,20 @@ export function buildNodeWithSN(
map, map,
skipChild: false, skipChild: false,
hackCss, hackCss,
afterAppend,
}); });
if (!childNode) { if (!childNode) {
console.warn('Failed to rebuild', childN); console.warn('Failed to rebuild', childN);
} else { continue;
node.appendChild(childNode); }
node.appendChild(childNode);
if (afterAppend) {
afterAppend(childNode);
} }
} }
} }
return node as INode; return node as INode;
} }
@@ -274,15 +288,17 @@ function rebuild(
doc: Document; doc: Document;
onVisit?: (node: INode) => unknown; onVisit?: (node: INode) => unknown;
hackCss?: boolean; hackCss?: boolean;
afterAppend?: (n: INode) => unknown;
}, },
): [Node | null, idNodeMap] { ): [Node | null, idNodeMap] {
const { doc, onVisit, hackCss = true } = options; const { doc, onVisit, hackCss = true, afterAppend } = options;
const idNodeMap: idNodeMap = {}; const idNodeMap: idNodeMap = {};
const node = buildNodeWithSN(n, { const node = buildNodeWithSN(n, {
doc, doc,
map: idNodeMap, map: idNodeMap,
skipChild: false, skipChild: false,
hackCss, hackCss,
afterAppend,
}); });
visit(idNodeMap, (visitedNode) => { visit(idNodeMap, (visitedNode) => {
if (onVisit) { if (onVisit) {

View File

@@ -196,6 +196,34 @@ export function _isBlockedElement(
return false; return false;
} }
// https://stackoverflow.com/a/36155560
function onceIframeLoaded(
iframeEl: HTMLIFrameElement,
listener: () => unknown,
) {
const win = iframeEl.contentWindow;
if (!win) {
return;
}
// document is loading
if (win.document.readyState !== 'complete') {
iframeEl.addEventListener('load', listener);
return;
}
// check blank frame for Chrome
const blankUrl = 'about:blank';
if (
win.location.href !== blankUrl ||
iframeEl.src === blankUrl ||
iframeEl.src === ''
) {
listener();
return;
}
// use default listener
iframeEl.addEventListener('load', listener);
}
function serializeNode( function serializeNode(
n: Node, n: Node,
options: { options: {
@@ -215,11 +243,18 @@ function serializeNode(
maskInputOptions = {}, maskInputOptions = {},
recordCanvas, recordCanvas,
} = options; } = options;
// Only record root id when document object is not the base document
let rootId: number | undefined;
if (((doc as unknown) as INode).__sn) {
const docId = ((doc as unknown) as INode).__sn.id;
rootId = docId === 1 ? undefined : docId;
}
switch (n.nodeType) { switch (n.nodeType) {
case n.DOCUMENT_NODE: case n.DOCUMENT_NODE:
return { return {
type: NodeType.Document, type: NodeType.Document,
childNodes: [], childNodes: [],
rootId,
}; };
case n.DOCUMENT_TYPE_NODE: case n.DOCUMENT_TYPE_NODE:
return { return {
@@ -227,6 +262,7 @@ function serializeNode(
name: (n as DocumentType).name, name: (n as DocumentType).name,
publicId: (n as DocumentType).publicId, publicId: (n as DocumentType).publicId,
systemId: (n as DocumentType).systemId, systemId: (n as DocumentType).systemId,
rootId,
}; };
case n.ELEMENT_NODE: case n.ELEMENT_NODE:
const needBlock = _isBlockedElement( const needBlock = _isBlockedElement(
@@ -318,6 +354,7 @@ function serializeNode(
if ((n as HTMLElement).scrollTop) { if ((n as HTMLElement).scrollTop) {
attributes.rr_scrollTop = (n as HTMLElement).scrollTop; attributes.rr_scrollTop = (n as HTMLElement).scrollTop;
} }
// block element
if (needBlock) { if (needBlock) {
const { width, height } = (n as HTMLElement).getBoundingClientRect(); const { width, height } = (n as HTMLElement).getBoundingClientRect();
attributes = { attributes = {
@@ -326,6 +363,10 @@ function serializeNode(
rr_height: `${height}px`, rr_height: `${height}px`,
}; };
} }
// iframe
if (tagName === 'iframe') {
delete attributes.src;
}
return { return {
type: NodeType.Element, type: NodeType.Element,
tagName, tagName,
@@ -333,6 +374,7 @@ function serializeNode(
childNodes: [], childNodes: [],
isSVG: isSVGElement(n as Element) || undefined, isSVG: isSVGElement(n as Element) || undefined,
needBlock, needBlock,
rootId,
}; };
case n.TEXT_NODE: case n.TEXT_NODE:
// The parent node may not be a html element which has a tagName attribute. // The parent node may not be a html element which has a tagName attribute.
@@ -351,16 +393,19 @@ function serializeNode(
type: NodeType.Text, type: NodeType.Text,
textContent: textContent || '', textContent: textContent || '',
isStyle, isStyle,
rootId,
}; };
case n.CDATA_SECTION_NODE: case n.CDATA_SECTION_NODE:
return { return {
type: NodeType.CDATA, type: NodeType.CDATA,
textContent: '', textContent: '',
rootId,
}; };
case n.COMMENT_NODE: case n.COMMENT_NODE:
return { return {
type: NodeType.Comment, type: NodeType.Comment,
textContent: (n as Comment).textContent || '', textContent: (n as Comment).textContent || '',
rootId,
}; };
default: default:
return false; return false;
@@ -472,6 +517,8 @@ export function serializeNodeWithId(
slimDOMOptions: SlimDOMOptions; slimDOMOptions: SlimDOMOptions;
recordCanvas?: boolean; recordCanvas?: boolean;
preserveWhiteSpace?: boolean; preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown;
}, },
): serializedNodeWithId | null { ): serializedNodeWithId | null {
const { const {
@@ -484,6 +531,8 @@ export function serializeNodeWithId(
maskInputOptions = {}, maskInputOptions = {},
slimDOMOptions, slimDOMOptions,
recordCanvas = false, recordCanvas = false,
onSerialize,
onIframeLoad,
} = options; } = options;
let { preserveWhiteSpace = true } = options; let { preserveWhiteSpace = true } = options;
const _serializedNode = serializeNode(n, { const _serializedNode = serializeNode(n, {
@@ -521,6 +570,9 @@ export function serializeNodeWithId(
return null; // slimDOM return null; // slimDOM
} }
map[id] = n as INode; map[id] = n as INode;
if (onSerialize) {
onSerialize(n as INode);
}
let recordChild = !skipChild; let recordChild = !skipChild;
if (serializedNode.type === NodeType.Element) { if (serializedNode.type === NodeType.Element) {
recordChild = recordChild && !serializedNode.needBlock; recordChild = recordChild && !serializedNode.needBlock;
@@ -552,12 +604,44 @@ export function serializeNodeWithId(
slimDOMOptions, slimDOMOptions,
recordCanvas, recordCanvas,
preserveWhiteSpace, preserveWhiteSpace,
onSerialize,
onIframeLoad,
}); });
if (serializedChildNode) { if (serializedChildNode) {
serializedNode.childNodes.push(serializedChildNode); serializedNode.childNodes.push(serializedChildNode);
} }
} }
} }
if (
serializedNode.type === NodeType.Element &&
serializedNode.tagName === 'iframe'
) {
onceIframeLoaded(n as HTMLIFrameElement, () => {
const iframeDoc = (n as HTMLIFrameElement).contentDocument;
if (iframeDoc && onIframeLoad) {
const serializedIframeNode = serializeNodeWithId(iframeDoc, {
doc: iframeDoc,
map,
blockClass,
blockSelector,
skipChild: false,
inlineStylesheet,
maskInputOptions,
slimDOMOptions,
recordCanvas,
preserveWhiteSpace,
onSerialize,
onIframeLoad,
});
if (serializedIframeNode) {
onIframeLoad(n as INode, serializedIframeNode);
}
}
});
}
return serializedNode; return serializedNode;
} }
@@ -570,6 +654,9 @@ function snapshot(
slimDOM?: boolean | SlimDOMOptions; slimDOM?: boolean | SlimDOMOptions;
recordCanvas?: boolean; recordCanvas?: boolean;
blockSelector?: string | null; blockSelector?: string | null;
preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown;
}, },
): [serializedNodeWithId | null, idNodeMap] { ): [serializedNodeWithId | null, idNodeMap] {
const { const {
@@ -579,6 +666,9 @@ function snapshot(
blockSelector = null, blockSelector = null,
maskAllInputs = false, maskAllInputs = false,
slimDOM = false, slimDOM = false,
preserveWhiteSpace,
onSerialize,
onIframeLoad,
} = options || {}; } = options || {};
const idNodeMap: idNodeMap = {}; const idNodeMap: idNodeMap = {};
const maskInputOptions: MaskInputOptions = const maskInputOptions: MaskInputOptions =
@@ -632,6 +722,9 @@ function snapshot(
maskInputOptions, maskInputOptions,
slimDOMOptions, slimDOMOptions,
recordCanvas, recordCanvas,
preserveWhiteSpace,
onSerialize,
onIframeLoad,
}), }),
idNodeMap, idNodeMap,
]; ];

View File

@@ -47,13 +47,16 @@ export type commentNode = {
textContent: string; textContent: string;
}; };
export type serializedNode = export type serializedNode = (
| documentNode | documentNode
| documentTypeNode | documentTypeNode
| elementNode | elementNode
| textNode | textNode
| cdataNode | cdataNode
| commentNode; | commentNode
) & {
rootId?: number;
};
export type serializedNodeWithId = serializedNode & { id: number }; export type serializedNodeWithId = serializedNode & { id: number };

View File

@@ -277,3 +277,135 @@ exports[`[html file]: with-style-sheet-with-import.html 1`] = `
</head><body> </head><body>
</body></html>" </body></html>"
`; `;
exports[`iframe integration tests 1`] = `
"{
\\"type\\": 0,
\\"childNodes\\": [
{
\\"type\\": 1,
\\"name\\": \\"html\\",
\\"publicId\\": \\"\\",
\\"systemId\\": \\"\\",
\\"id\\": 2
},
{
\\"type\\": 2,
\\"tagName\\": \\"html\\",
\\"attributes\\": {
\\"lang\\": \\"en\\"
},
\\"childNodes\\": [
{
\\"type\\": 2,
\\"tagName\\": \\"head\\",
\\"attributes\\": {},
\\"childNodes\\": [
{
\\"type\\": 3,
\\"textContent\\": \\"\\\\n \\",
\\"id\\": 5
},
{
\\"type\\": 2,
\\"tagName\\": \\"meta\\",
\\"attributes\\": {
\\"charset\\": \\"UTF-8\\"
},
\\"childNodes\\": [],
\\"id\\": 6
},
{
\\"type\\": 3,
\\"textContent\\": \\"\\\\n \\",
\\"id\\": 7
},
{
\\"type\\": 2,
\\"tagName\\": \\"meta\\",
\\"attributes\\": {
\\"name\\": \\"viewport\\",
\\"content\\": \\"width=device-width, initial-scale=1.0\\"
},
\\"childNodes\\": [],
\\"id\\": 8
},
{
\\"type\\": 3,
\\"textContent\\": \\"\\\\n \\",
\\"id\\": 9
},
{
\\"type\\": 2,
\\"tagName\\": \\"title\\",
\\"attributes\\": {},
\\"childNodes\\": [
{
\\"type\\": 3,
\\"textContent\\": \\"Main\\",
\\"id\\": 11
}
],
\\"id\\": 10
},
{
\\"type\\": 3,
\\"textContent\\": \\"\\\\n \\",
\\"id\\": 12
}
],
\\"id\\": 4
},
{
\\"type\\": 3,
\\"textContent\\": \\"\\\\n \\",
\\"id\\": 13
},
{
\\"type\\": 2,
\\"tagName\\": \\"body\\",
\\"attributes\\": {},
\\"childNodes\\": [
{
\\"type\\": 3,
\\"textContent\\": \\"\\\\n \\",
\\"id\\": 15
},
{
\\"type\\": 2,
\\"tagName\\": \\"iframe\\",
\\"attributes\\": {
\\"id\\": \\"one\\"
},
\\"childNodes\\": [],
\\"id\\": 16
},
{
\\"type\\": 3,
\\"textContent\\": \\"\\\\n \\",
\\"id\\": 17
},
{
\\"type\\": 2,
\\"tagName\\": \\"iframe\\",
\\"attributes\\": {
\\"id\\": \\"two\\"
},
\\"childNodes\\": [],
\\"id\\": 18
},
{
\\"type\\": 3,
\\"textContent\\": \\"\\\\n \\\\n\\\\n\\",
\\"id\\": 19
}
],
\\"id\\": 14
}
],
\\"id\\": 3
}
],
\\"id\\": 1
}"
`;

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Frame 1</title>
</head>
<body>
frame 1
<iframe id="three" frameborder="0"></iframe>
<iframe id="four" src="./frame2.html" frameborder="0"></iframe>
</body>
</html>

View File

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Frame 2</title>
</head>
<body>
frame 2
</body>
</html>

View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Main</title>
</head>
<body>
<iframe id="one"></iframe>
<iframe id="two" src="./frame1.html"></iframe>
</body>
</html>

View File

@@ -119,3 +119,50 @@ describe('integration tests', function (this: ISuite) {
}).timeout(5000); }).timeout(5000);
} }
}); });
describe('iframe integration tests', function (this: ISuite) {
const iframeHtml = path.join(__dirname, 'iframe-html/main.html');
const raw = fs.readFileSync(iframeHtml, 'utf-8');
before(async () => {
this.server = await server();
this.browser = await puppeteer.launch({
// headless: false,
});
const bundle = await rollup.rollup({
input: path.resolve(__dirname, '../src/index.ts'),
plugins: [typescript()],
});
const { code } = await bundle.generate({
name: 'rrweb',
format: 'iife',
});
this.code = code;
});
after(async () => {
await this.browser.close();
await this.server.close();
});
it('snapshot async iframes', async () => {
const page: puppeteer.Page = await this.browser.newPage();
// console for debug
// tslint:disable-next-line: no-console
page.on('console', (msg) => console.log(msg.text()));
await page.goto(`http://localhost:3030/html`);
await page.setContent(raw, {
waitUntil: 'load',
});
const snapshotResult = JSON.stringify(
await page.evaluate(`${this.code};
rrweb.snapshot(document)[0];
`),
null,
2,
);
const result = matchSnapshot(snapshotResult, __filename, this.title);
assert(result.pass, result.pass ? '' : result.report());
}).timeout(5000);
});

View File

@@ -5,10 +5,12 @@ export declare function buildNodeWithSN(n: serializedNodeWithId, options: {
map: idNodeMap; map: idNodeMap;
skipChild?: boolean; skipChild?: boolean;
hackCss: boolean; hackCss: boolean;
afterAppend?: (n: INode) => unknown;
}): INode | null; }): INode | null;
declare function rebuild(n: serializedNodeWithId, options: { declare function rebuild(n: serializedNodeWithId, options: {
doc: Document; doc: Document;
onVisit?: (node: INode) => unknown; onVisit?: (node: INode) => unknown;
hackCss?: boolean; hackCss?: boolean;
afterAppend?: (n: INode) => unknown;
}): [Node | null, idNodeMap]; }): [Node | null, idNodeMap];
export default rebuild; export default rebuild;

View File

@@ -15,6 +15,8 @@ export declare function serializeNodeWithId(n: Node | INode, options: {
slimDOMOptions: SlimDOMOptions; slimDOMOptions: SlimDOMOptions;
recordCanvas?: boolean; recordCanvas?: boolean;
preserveWhiteSpace?: boolean; preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown;
}): serializedNodeWithId | null; }): serializedNodeWithId | null;
declare function snapshot(n: Document, options?: { declare function snapshot(n: Document, options?: {
blockClass?: string | RegExp; blockClass?: string | RegExp;
@@ -23,6 +25,9 @@ declare function snapshot(n: Document, options?: {
slimDOM?: boolean | SlimDOMOptions; slimDOM?: boolean | SlimDOMOptions;
recordCanvas?: boolean; recordCanvas?: boolean;
blockSelector?: string | null; blockSelector?: string | null;
preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown;
}): [serializedNodeWithId | null, idNodeMap]; }): [serializedNodeWithId | null, idNodeMap];
export declare function visitSnapshot(node: serializedNodeWithId, onVisit: (node: serializedNodeWithId) => unknown): void; export declare function visitSnapshot(node: serializedNodeWithId, onVisit: (node: serializedNodeWithId) => unknown): void;
export declare function cleanupSnapshot(): void; export declare function cleanupSnapshot(): void;

4
typings/types.d.ts vendored
View File

@@ -40,7 +40,9 @@ export declare type commentNode = {
type: NodeType.Comment; type: NodeType.Comment;
textContent: string; textContent: string;
}; };
export declare type serializedNode = documentNode | documentTypeNode | elementNode | textNode | cdataNode | commentNode; export declare type serializedNode = (documentNode | documentTypeNode | elementNode | textNode | cdataNode | commentNode) & {
rootId?: number;
};
export declare type serializedNodeWithId = serializedNode & { export declare type serializedNodeWithId = serializedNode & {
id: number; id: number;
}; };