From 41fb73e83e36d925b85a2d2f3d7746f59212bbf0 Mon Sep 17 00:00:00 2001 From: Frank Cheung Date: Sun, 25 Sep 2022 13:13:31 +0800 Subject: [PATCH] fix: add to fix relative error in iframe --- package-lock.json | 2 +- src/dom/document-cloner.ts | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index f972f71..77c197a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,7 +5,7 @@ "requires": true, "packages": { "": { - "version": "1.4.0", + "version": "1.4.1", "license": "MIT", "dependencies": { "css-line-break": "^2.1.0", diff --git a/src/dom/document-cloner.ts b/src/dom/document-cloner.ts index 08faa29..ef22a77 100644 --- a/src/dom/document-cloner.ts +++ b/src/dom/document-cloner.ts @@ -129,11 +129,17 @@ export class DocumentCloner { return iframe; }); + const adoptedNode = documentClone.adoptNode(this.documentElement); + /** + * The baseURI of the document will be lost after documentClone.open(). + * We can avoid it by adding element. + * */ + addBase(adoptedNode, documentClone); documentClone.open(); documentClone.write(`${serializeDoctype(document.doctype)}`); // Chrome scrolls the parent document for some reason after the write to the cloned window??? restoreOwnerScroll(this.referenceElement.ownerDocument, scrollX, scrollY); - documentClone.replaceChild(documentClone.adoptNode(this.documentElement), documentClone.documentElement); + documentClone.replaceChild(adoptedNode, documentClone.documentElement); documentClone.close(); return iframeLoad; @@ -635,3 +641,10 @@ const createStyles = (body: HTMLElement, styles: string) => { body.appendChild(style); } }; + +const addBase = (targetELement: HTMLElement, referenceDocument: Document) => { + const baseNode = referenceDocument.createElement('base'); + baseNode.href = referenceDocument.baseURI; + const headEle = targetELement.getElementsByTagName('head').item(0); + headEle?.insertBefore(baseNode, headEle?.firstChild ?? null); +};