diff --git a/package.json b/package.json index 6f56531c..04fde37f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rrweb-snapshot", - "version": "0.4.3", + "version": "0.4.4", "description": "rrweb's component to take a snapshot of DOM, aka DOM serializer", "main": "dist/index.js", "module": "dist/module.js", diff --git a/src/snapshot.ts b/src/snapshot.ts index c948fa14..5674e86d 100644 --- a/src/snapshot.ts +++ b/src/snapshot.ts @@ -28,9 +28,29 @@ function getCssRulesString(s: CSSStyleSheet): string | null { } } +function extractOrigin(url: string): string { + let origin; + if (url.indexOf('//') > -1) { + origin = url + .split('/') + .slice(0, 3) + .join('/'); + } else { + origin = url.split('/')[0]; + } + origin = origin.split('?')[0]; + return origin; +} + const URL_IN_CSS_REF = /url\((['"])([^'"]*)\1\)/gm; -function absoluteToStylesheet(cssText: string, href: string): string { +export function absoluteToStylesheet(cssText: string, href: string): string { return cssText.replace(URL_IN_CSS_REF, (_1, _2, filePath) => { + if (!/^[./]/.test(filePath)) { + return `url('${filePath}')`; + } + if (filePath[0] === '/') { + return `url('${extractOrigin(href) + filePath}')`; + } const stack = href.split('/'); const parts = filePath.split('/'); stack.pop(); diff --git a/test/snapshot.test.ts b/test/snapshot.test.ts new file mode 100644 index 00000000..0720f120 --- /dev/null +++ b/test/snapshot.test.ts @@ -0,0 +1,31 @@ +import 'mocha'; +import { expect } from 'chai'; +import { absoluteToStylesheet } from '../src/snapshot'; + +describe('absolute url to stylesheet', () => { + const href = 'http://localhost/css/style.css'; + + it('can handle same level path', () => { + expect(absoluteToStylesheet('url("./a.jpg")', href)).to.equal( + `url('http://localhost/css/a.jpg')`, + ); + }); + + it('can handle parent level path', () => { + expect(absoluteToStylesheet('url("../a.jpg")', href)).to.equal( + `url('http://localhost/a.jpg')`, + ); + }); + + it('can handle absolute path', () => { + expect(absoluteToStylesheet('url("/a.jpg")', href)).to.equal( + `url('http://localhost/a.jpg')`, + ); + }); + + it('can handle external path', () => { + expect( + absoluteToStylesheet('url("http://localhost/a.jpg")', href), + ).to.equal(`url('http://localhost/a.jpg')`); + }); +});