Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions karma.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ module.exports = config => config.set({
{ pattern: 'test/**/*.test.js', watched: false }
],

proxies: {
// useful when the contents of a fake asset do not matter
'/_/': 'localhost/'
},

// create dedicated bundles for src, test helpers, and each test suite
preprocessors: {
'src/index.js': ['rollup'],
Expand Down
51 changes: 51 additions & 0 deletions packages/dom/src/serialize-frames.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,55 @@
import serializeDOM from './serialize-dom';

// List of attributes that accept URIs that should be transformed
const URI_ATTRS = ['href', 'src', 'srcset', 'poster', 'background'];
const URI_SELECTOR = URI_ATTRS.map(a => `[${a}]`).join(',') + (
',[style*="url("]'); // include elements with url style attributes

// A loose srcset image candidate regex split into capture groups
// https://html.spec.whatwg.org/multipage/images.html#srcset-attribute
const SRCSET_REGEX = /(\s*)([^,]\S*[^,])((?:\s+[^,]+)*\s*(?:,|$))/g;

// A loose CSS url() regex split into capture groups
const CSS_URL_REGEX = /(url\((["']?))((?:\\.|(?!\2).|[^)])+)(\2\))/g;

// Transforms URL attributes within a document to be fully qualified URLs. This is necessary when
// embedded documents are serialized and their contents become root-relative.
function transformRelativeUrls(dom) {
// transform style elements that might contain URLs
for (let style of dom.querySelectorAll('style')) {
style.innerHTML &&= style.innerHTML
.replace(CSS_URL_REGEX, (_, $1, $2, uri, $4) => (
`${$1}${new URL(uri, style.baseURI).href}${$4}`
));
}

// transform element attributes that might contain URLs
for (let el of dom.querySelectorAll(URI_SELECTOR)) {
for (let attr of URI_ATTRS.concat('style')) {
if (!(attr in el) || !el[attr] || !el.hasAttribute(attr)) continue;
let value = el[attr];

if (attr === 'style') {
// transform inline style url() usage
value = el.getAttribute('style')
.replace(CSS_URL_REGEX, (_, $1, $2, uri, $4) => (
`${$1}${new URL(uri, el.baseURI).href}${$4}`
));
} else if (attr === 'srcset') {
// transform each srcset URL
value = value.replace(SRCSET_REGEX, (_, $1, uri, $3) => (
`${$1}${new URL(uri, el.baseURI).href}${$3}`
));
} else {
// resolve the URL with the node's base URI
value = new URL(value, el.baseURI).href;
}

el.setAttribute(attr, value);
}
}
}

// Recursively serializes iframe documents into srcdoc attributes.
export default function serializeFrames(dom, clone, { enableJavaScript }) {
for (let frame of dom.querySelectorAll('iframe')) {
Expand All @@ -22,6 +72,7 @@ export default function serializeFrames(dom, clone, { enableJavaScript }) {

// recersively serialize contents
let serialized = serializeDOM({
domTransformation: transformRelativeUrls,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dom: frame.contentDocument,
enableJavaScript
});
Expand Down
25 changes: 25 additions & 0 deletions packages/dom/test/serialize-frames.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ describe('serializeFrames', () => {
<iframe id="frame-empty-self" src="javascript:void(
Object.defineProperty(this.document, 'documentElement', { value: null })
)"></iframe>
<iframe id="frame-with-urls" src="javascript:void(
(this.document.body.background = '_/bg.png'),
(this.document.body.innerHTML = \`
<style>@font-face { src: url('_/font.woff2') }</style>
<h1 style='background-image:url(_/head.png)'>Testing</h1>
<link rel='stylesheet' href='_/style.css'>
<img src='_/img.gif' srcset='/_/img.png 2x,
//example.com/img.png 400w'>
<video poster='_/poster.png'>\`)
)"></iframe>
`);

let $frameInput = await getFrame('frame-input');
Expand Down Expand Up @@ -82,6 +92,21 @@ describe('serializeFrames', () => {
].join('')));
});

it('serializes iframes internal URLs', () => {
let url = uri => new URL(uri, document.URL).href;

expect($('#frame-with-urls')[0].getAttribute('srcdoc')).toBe([
`<!DOCTYPE html><html><head></head><body background="${url('_/bg.png')}">`,
`<style>@font-face { src: url('${url('_/font.woff2')}') }</style>`,
`<h1 style="background-image:url(${url('_/head.png')})">Testing</h1>`,
`<link rel="stylesheet" href="${url('_/style.css')}">`,
`<img src="${url('_/img.gif')}" srcset="${url('/_/img.png')} 2x,`,
' http://example.com/img.png 400w">',
`<video poster="${url('_/poster.png')}"></video>`
// account for indentation in the fixture
].join(' '.repeat(12)) + '</body></html>');
});

it('does not serialize iframes with CORS', () => {
expect($('#frame-external')[0].getAttribute('src')).toBe('https://example.com');
expect($('#frame-external-fail')[0].getAttribute('src')).toBe('https://google.com');
Expand Down