Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
fix(snapshotter): do not treat synthetic shadow roots as shadow roots (#42859)
Dmitry Gozman3847b985e83b
diff --git a/packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts b/packages/playwright-core/src/server/trace/recorder/snapshotterInjected.tsindex a94775ef9a..00e5a47978 100644--- a/packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts+++ b/packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts@@ -94,8 +94,16 @@ export function frameSnapshotStreamer(snapshotStreamer: string, removeNoScript:private _observer: MutationObserver;private _observedDocument: Document | undefined;private _targetGeneration = 0;+ private _nativeShadowRoot: typeof ShadowRoot;+ private _nativeFirstChild: (this: Node) => Node | null;+ private _nativeNextSibling: (this: Node) => Node | null;constructor() {+ // Some pages overwrite the following native functions, so capture them in advance.+ this._nativeShadowRoot = window.ShadowRoot;+ this._nativeFirstChild = Object.getOwnPropertyDescriptor(window.Node.prototype, 'firstChild')!.get!;+ this._nativeNextSibling = Object.getOwnPropertyDescriptor(window.Node.prototype, 'nextSibling')!.get!;+const invalidateCSSGroupingRule = (rule: CSSGroupingRule) => {if (rule.parentStyleSheet)this._invalidateStyleSheet(rule.parentStyleSheet);@@ -160,6 +168,12 @@ export function frameSnapshotStreamer(snapshotStreamer: string, removeNoScript:});}+ private _shadowRoot(element: Element): ShadowRoot | null {+ // Some frameworks define fake `element.shadowRoot` properties, thus an `instanceof` check.+ const shadowRoot = element.shadowRoot;+ return shadowRoot instanceof this._nativeShadowRoot ? shadowRoot : null;+ }+private _interceptNativeMethod(obj: any, method: string, cb: (thisObj: any, result: any) => void) {const native = obj[method] as Function;if (!native)@@ -272,11 +286,11 @@ export function frameSnapshotStreamer(snapshotStreamer: string, removeNoScript:const visitNode = (node: Node | ShadowRoot) => {resetCachedData(node);if (node.nodeType === Node.ELEMENT_NODE) {- const element = node as Element;- if (element.shadowRoot)- visitNode(element.shadowRoot);+ const shadowRoot = this._shadowRoot(node as Element);+ if (shadowRoot)+ visitNode(shadowRoot);}- for (let child = node.firstChild; child; child = child.nextSibling)+ for (let child = this._nativeFirstChild.call(node); child; child = this._nativeNextSibling.call(child))visitNode(child);};visitNode(document.documentElement);@@ -515,9 +529,10 @@ export function frameSnapshotStreamer(snapshotStreamer: string, removeNoScript:expectValue(element.scrollLeft);attrs[kScrollLeftAttribute] = '' + element.scrollLeft;}- if (element.shadowRoot) {+ const shadowRoot = this._shadowRoot(element);+ if (shadowRoot) {++shadowDomNesting;- visitChild(element.shadowRoot);+ visitChild(shadowRoot);--shadowDomNesting;}if ((element as any).__playwright_target__ === this._targetGeneration) {@@ -532,7 +547,7 @@ export function frameSnapshotStreamer(snapshotStreamer: string, removeNoScript:this._fakeBase.setAttribute('href', document.baseURI);visitChild(this._fakeBase);}- for (let child = node.firstChild; child; child = child.nextSibling)+ for (let child = this._nativeFirstChild.call(node); child; child = this._nativeNextSibling.call(child))visitChild(child);if (nodeName === 'HEAD')--headNesting;diff --git a/tests/assets/synthetic-shadow.html b/tests/assets/synthetic-shadow.htmlnew file mode 100644index 0000000000..180a6da9f7--- /dev/null+++ b/tests/assets/synthetic-shadow.html@@ -0,0 +1,75 @@+<!DOCTYPE html>+<style>+ /* Document-level CSS, the way LWC emits it: an attribute-scoped rule plus a plain class rule. */+ [my-tok] .box { border: 4px solid rebeccapurple; padding: 4px; }+ .icon { width: 24px; height: 24px; fill: rebeccapurple; }+</style>+<script>+// Minimal imitation of @lwc/synthetic-shadow. A synthetic "shadow root" is a DocumentFragment+// with a swapped prototype, its content physically lives inside the host, and patched accessors+// hide that from the page: root.firstChild returns the host's real children, while host.firstChild+// returns the "light DOM" nodes that were slotted, which physically live inside the <slot>.+(() => {+ const NativeShadowRoot = window.ShadowRoot;+ const nativeAttachShadow = Element.prototype.attachShadow;+ const nativeShadowRootGetter = Object.getOwnPropertyDescriptor(Element.prototype, 'shadowRoot').get;+ const nativeFirstChildGetter = Object.getOwnPropertyDescriptor(Node.prototype, 'firstChild').get;+ const nativeChildNodesGetter = Object.getOwnPropertyDescriptor(Node.prototype, 'childNodes').get;+ const nativeAppendChild = Node.prototype.appendChild;+ const roots = new WeakMap(); // host -> synthetic root+ const hosts = new WeakMap(); // synthetic root -> host++ function SyntheticShadowRoot() { throw new TypeError('Illegal constructor'); }+ SyntheticShadowRoot.prototype = Object.create(DocumentFragment.prototype, {+ mode: { get() { return 'open'; } },+ host: { get() { return hosts.get(this); } },+ firstChild: { get() { return nativeFirstChildGetter.call(hosts.get(this)); } },+ childNodes: { get() { return nativeChildNodesGetter.call(hosts.get(this)); } },+ appendChild: { value(node) { return nativeAppendChild.call(hosts.get(this), node); } },+ });+ // `root instanceof ShadowRoot` is true for both native and synthetic roots.+ Object.defineProperty(SyntheticShadowRoot, Symbol.hasInstance, {+ value: object => object instanceof NativeShadowRoot || Object.getPrototypeOf(object) === SyntheticShadowRoot.prototype,+ });+ window.ShadowRoot = SyntheticShadowRoot;++ Element.prototype.attachShadow = function(options) {+ if (!options['$$lwc-synthetic-mode'])+ return nativeAttachShadow.call(this, options);+ const root = document.createDocumentFragment();+ Object.setPrototypeOf(root, SyntheticShadowRoot.prototype);+ roots.set(this, root);+ hosts.set(root, this);+ return root;+ };+ Object.defineProperty(Element.prototype, 'shadowRoot', {+ configurable: true,+ get() { return roots.get(this) || nativeShadowRootGetter.call(this); },+ });+ Object.defineProperty(Node.prototype, 'firstChild', {+ configurable: true,+ get() {+ if (!roots.has(this))+ return nativeFirstChildGetter.call(this);+ const slot = this.querySelector('slot');+ return slot ? nativeFirstChildGetter.call(slot) : null;+ },+ });+})();+</script>+<my-card id="synth" my-tok></my-card>+<my-card id="native"></my-card>+<script>+ const template = '<div class="box" my-tok><svg class="icon" my-tok viewBox="0 0 10 10"><rect width="10" height="10"></rect></svg><slot></slot></div>';++ const synth = document.getElementById('synth').attachShadow({ mode: 'open', '$$lwc-synthetic-mode': true });+ const tpl = document.createElement('template');+ tpl.innerHTML = template;+ synth.appendChild(tpl.content);+ const slotted = document.createElement('span');+ slotted.textContent = 'slotted content';+ document.getElementById('synth').querySelector('slot').appendChild(slotted);++ const native = document.getElementById('native').attachShadow({ mode: 'open' });+ native.innerHTML = '<style>.box { border: 4px solid seagreen; padding: 4px; } .icon { width: 24px; height: 24px; fill: seagreen; }</style>' + template.replace(/ my-tok/g, '');+</script>diff --git a/tests/library/trace-viewer.spec.ts b/tests/library/trace-viewer.spec.tsindex 3bad29611a..18b251dbc2 100644--- a/tests/library/trace-viewer.spec.ts+++ b/tests/library/trace-viewer.spec.ts@@ -1254,6 +1254,25 @@ test('should register custom elements', async ({ page, server, runAndTrace }) =>await expect(frame.getByText('worldhello')).toBeVisible();});+test('should not treat synthetic shadow root as a shadow root', async ({ page, server, runAndTrace }) => {+ test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42772' });+ const traceViewer = await runAndTrace(async () => {+ await page.goto(server.PREFIX + '/synthetic-shadow.html');+ await page.evaluate(() => {});+ });++ const frame = await traceViewer.snapshotFrame('Evaluate');+ // Synthetic host: content is physically in the light DOM, styled by document-level CSS.+ await expect(frame.locator('#synth .box')).toHaveCSS('border-top-width', '4px');+ await expect(frame.locator('#synth .icon')).toHaveCSS('width', '24px');+ await expect(frame.locator('#synth .icon')).toHaveCSS('fill', 'rgb(102, 51, 153)');+ await expect(frame.locator('#synth slot')).toHaveText('slotted content');+ // Native host: styled by its own <style> inside the shadow root.+ await expect(frame.locator('#native .box')).toHaveCSS('border-top-width', '4px');+ await expect(frame.locator('#native .icon')).toHaveCSS('width', '24px');+ await expect(frame.locator('#native .icon')).toHaveCSS('fill', 'rgb(46, 139, 87)');+});+test('should highlight target elements', async ({ page, runAndTrace, browserName }) => {const traceViewer = await runAndTrace(async () => {await page.setContent(`