Skip to content
Draft
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
17 changes: 16 additions & 1 deletion src/playground-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,14 +567,29 @@ export class PlaygroundProject extends LitElement {
iframeWindow.postMessage(message, '*', transfer);
}

/**
* Transforms HTML on each preview request without modifying the project
* source files. Use this to insert monitoring or debug scripts into the
* preview HTML.
*/
previewHtmlTransform?: (html: string) => string;

private async _getFile(name: string): Promise<SampleFile | HttpError> {
if (this._build === undefined) {
return {
status: /* Service Unavailable */ 503,
body: 'Playground build not started',
};
}
return this._build.getFile(name);
const file = await this._build.getFile(name);
if (
this.previewHtmlTransform &&
'content' in file &&
file.contentType?.split(';')[0] === 'text/html'
) {
return {...file, content: this.previewHtmlTransform(file.content)};
}
return file;
}

/**
Expand Down
22 changes: 22 additions & 0 deletions src/test/playground-ide_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import {assert} from '@esm-bundle/chai';
import {waitUntil} from '@open-wc/testing';
import {html, render} from 'lit';
import {PlaygroundIde} from '../playground-ide.js';
import '../playground-ide.js';
Expand Down Expand Up @@ -152,6 +153,27 @@ suite('playground-ide', () => {
await assertPreviewContains('Hello HTML');
});

test('transforms served HTML without changing source files', async () => {
const project = document.createElement('playground-project');
project.sandboxBaseUrl = '/';
project.previewHtmlTransform = (source) => `<meta name="instrumented">${source}`;
const compiled = new Promise<void>((resolve) => {
project.addEventListener('compileDone', () => resolve(), {once: true});
});
project.config = {files: {'index.html': {content: '<p>Original</p>'}}};
container.appendChild(project);
await compiled;
await waitUntil(() => project.baseUrl !== undefined);
const iframe = document.createElement('iframe');
iframe.src = new URL('index.html', project.baseUrl).href;
container.appendChild(iframe);
await waitUntil(() => Boolean(
iframe.contentDocument?.querySelector('meta[name="instrumented"]')
));
assert.equal(project.files![0].content, '<p>Original</p>');
assert.isFalse(project.modified);
});

test('handles multiple script tags', async () => {
render(
html`
Expand Down