Skip to content

Fix Custom HTML block preview not rendering on first load (#78576) - #78582

Closed
itzmekhokan wants to merge 7 commits into
WordPress:trunkfrom
itzmekhokan:fix/78576
Closed

itzmekhokan wants to merge 7 commits into
WordPress:trunkfrom
itzmekhokan:fix/78576

Conversation

@itzmekhokan

@itzmekhokan itzmekhokan commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

What?

Fixes a race condition in IsolatedSandBox that caused the Custom HTML block preview iframe to remain at zero height after adding or reloading content in the editor.

Fixes #78576.

Why?

After WordPress 7.0, the Custom HTML block preview uses IsolatedSandBox (via #77212) instead of a same-origin sandbox. The preview iframe relies on postMessage resize events to set its height. On first mount or when reopening a post, the initial resize message could be sent before the parent window's message listener was attached, leaving the iframe at height={0} and making the block appear blank in the editor.

How?

  • Schedule delayed resize messages inside the sandbox iframe so the parent listener receives them even when srcdoc loads synchronously.
  • Attach load listeners to nested iframes so preview height updates when embedded iframe content finishes loading.
  • Switch IsolatedSandBox to useLayoutEffect and re-sync the message listener whenever srcDoc changes.

Testing Instructions

  1. Create a new post and insert a Custom HTML block.
  2. Click Edit HTML, add <p>Hello World</p>, click Update.
  3. Confirm the preview renders immediately without refreshing.
  4. Save the post, close the editor, and reopen the post.
  5. Confirm the Custom HTML preview is visible on first load.
  6. Add HTML containing a nested iframe (e.g. <iframe src="https://example.com" width="400" height="300"></iframe>).
  7. Confirm the preview area sizes correctly (note: some third-party embeds may still not fully render in the isolated sandbox due to referrer restrictions from Remove sandbox allow-same-origin for core/html blocks #77212 — this is expected and separate from this fix).

Regression checks

Test plan

  • Custom HTML preview renders on first save without page refresh
  • Custom HTML preview renders when reopening a saved post
  • Preview renders inside the Edit HTML modal
  • Embed block previews still work
  • Cover block video background preview still works
  • npm run test:unit -- --testPathPattern="packages/components/src/sandbox/test" passes
  • npm run test:e2e -- test/e2e/specs/editor/blocks/html.spec.js passes

Use of AI Tools

AI assistance: Yes
Tool(s): Claude

The isolated SandBox iframe could miss its initial resize postMessage
before the parent listener was attached, leaving the preview at 0 height.
Schedule delayed resize messages, listen for nested iframe loads, and
re-sync the parent listener when srcDoc changes.
@itzmekhokan
itzmekhokan requested review from a team and ajitbohra as code owners May 22, 2026 15:23
@github-actions github-actions Bot added the [Package] Components /packages/components label May 22, 2026
@github-actions

github-actions Bot commented May 22, 2026 •

Copy link
Copy Markdown

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

Unlinked Accounts

The following contributors have not linked their GitHub and WordPress.org accounts: @nazmulasif, @jaideep-bishnoi, @doni32, @branostupak, @thewhitedrewcarey.

Contributors, please read how to link your accounts to ensure your work is properly credited in WordPress releases.

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Unlinked contributors: nazmulasif, jaideep-bishnoi, doni32, branostupak, thewhitedrewcarey.

Co-authored-by: itzmekhokan <khokansardar@git.wordpress.org>
Co-authored-by: alecgeatches <alecgeatches@git.wordpress.org>
Co-authored-by: t-hamano <wildworks@git.wordpress.org>
Co-authored-by: aduth <aduth@git.wordpress.org>
Co-authored-by: aaronjorbin <jorbin@git.wordpress.org>
Co-authored-by: anik-cse <mirmpro@git.wordpress.org>
Co-authored-by: andreawetzel <awetz583@git.wordpress.org>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

@aduth

aduth commented May 22, 2026

Copy link
Copy Markdown
Member

A time-based solution feels rather fragile, and could still suffer from the same type of race conditions if it takes longer than 100ms for the parent window to attach its event handler.

If parent window readiness timing is an issue, what if the messaging was two-way? So a parent frame could send a message to the sandbox indicating that it's ready, and the sandbox responding accordingly with the resize message.

@aduth
aduth requested a review from alecgeatches May 22, 2026 17:57
@alecgeatches

Copy link
Copy Markdown
Contributor

Thanks for this fix! I agree with @aduth above, syncing resizes through two-way postMessage feels like a better solution than a wait-and-hope. Side note, I didn't even realize postMessage was possible without allow-same-origin, but MDN (and existing code) says it's fine:

Script access to a frame's content is subject to the same-origin policy. Scripts cannot access most properties in other window objects if the script was loaded from a different origin, including scripts inside a frame accessing the frame's parent. Cross-origin communication can be achieved using Window.postMessage()

So allow-same-origin protects from DOM and cookie access, but it seems like it can still be used for two-way communication between the iframe and the page. I think it could work like:

  1. iframe adds a message listener for a 'ready' state from the editor. When that's received, send a message to apply a resize.
  2. iframe also sends a resize message when first loaded in case the iframe missed the 'ready' state during load as a backup.

On the editor side,

  1. Send a 'ready' state to the iframe when after it's mounted. It should be ready to resize at that point from the setup above.

The rest of the logic should work the same as before, I think.

@skorasaurus skorasaurus added the [Block] HTML Affects the the HTML Block label May 22, 2026
Replace delayed resize retries with a ready/resize handshake between
the parent frame and isolated iframe, per review feedback on WordPress#78582.
Add an explicit MessageEvent type for the embedded iframe handler
parameter to satisfy strict package type checking in CI.
@itzmekhokan

Copy link
Copy Markdown
Contributor Author

Thanks @aduth and @alecgeatches for the feedback! I've replaced the delayed retry approach with a two-way postMessage handshake:

Parent sends { action: 'ready' } after the resize listener is attached
Iframe responds with { action: 'resize', width, height }
Iframe also sends an initial resize on load as a backup if it missed the ready message during synchronous srcdoc loading
Unit tests updated and passing. Happy to adjust further if needed.

@t-hamano t-hamano added the [Type] Bug An existing feature does not function as intended label May 23, 2026
@github-project-automation github-project-automation Bot moved this to 🔎 Needs Review in WordPress 7.0 Editor Tasks May 23, 2026
@t-hamano t-hamano moved this from 🔎 Needs Review to 🐛 Punted to 7.0.1 in WordPress 7.0 Editor Tasks May 23, 2026
@t-hamano t-hamano added the Backport to WP Minor Release Pull request that needs to be backported to a WordPress minor release label May 23, 2026
@t-hamano t-hamano moved this from 🐛 Punted to 7.0.1 to 🔎 Needs Review in WordPress 7.0 Editor Tasks May 24, 2026
Comment thread packages/components/CHANGELOG.md Resolved
Co-authored-by: Aki Hamano <54422211+t-hamano@users.noreply.github.com>
@aaronjorbin

Copy link
Copy Markdown
Member

@alecgeatches @aduth Would y'all be able to take a look at the updated approach and make sure it's inline with what you were thinking?

@itzmekhokan can you take a look at the failing check and update the changelog accordingly?

@itzmekhokan

Copy link
Copy Markdown
Contributor Author

@alecgeatches @aduth Would y'all be able to take a look at the updated approach and make sure it's inline with what you were thinking?

@itzmekhokan can you take a look at the failing check and update the changelog accordingly?

@aaronjorbin I've updated the changelog.

@aduth aduth left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for updating the approach, I think this is looking like the right direction now. I left some review comments for you to consider.


const observer = new MutationObserver( function () {
sendResize();
attachIframeLoadListeners();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is going to continuously add event handlers any time there's a DOM mutation, which is a big memory and could become quite bad for performance. I would expect we'd only need to add listeners once.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — that would keep re-scanning and re-binding on every mutation. I added a WeakSet so each nested iframe gets its load listener exactly once. I kept the call inside the MutationObserver (rather than only running it once at init) because embeds can inject iframes after load, and the WeakSet ensures we only wire up newly-added ones.

Comment on lines +28 to +51
if ( ! data ) {
return null;
}

let message = data;

if ( 'string' === typeof message ) {
try {
message = JSON.parse( message );
} catch {
return null;
}
}

if (
'object' !== typeof message ||
null === message ||
! ( 'action' in message ) ||
'string' !== typeof ( message as SandBoxMessage ).action
) {
return null;
}

return message as SandBoxMessage;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe we could just rely on the try block to catch any the validation issues we're expecting, to simplify this?

Something more like:

Suggested change
if ( ! data ) {
return null;
}
let message = data;
if ( 'string' === typeof message ) {
try {
message = JSON.parse( message );
} catch {
return null;
}
}
if (
'object' !== typeof message ||
null === message ||
! ( 'action' in message ) ||
'string' !== typeof ( message as SandBoxMessage ).action
) {
return null;
}
return message as SandBoxMessage;
try {
const message = JSON.parse( data );
if ( typeof ( message as SandBoxMessage ).action === 'string' ) {
return message as SandBoxMessage;
}
} catch {}
return null;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Simplified to lean on the try block as suggested. One caveat: our own sandbox iframe posts the resize message as an object ({ action: 'resize', … }) rather than a JSON string, so a JSON.parse-only version would reject our own messages. I kept a typeof data === 'string' ? JSON.parse( data ) : data branch inside the try so both the object path and the string path (some embed providers) still work, and added a comment noting why.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I kept a typeof data === 'string' ? JSON.parse( data ) : data branch inside the try so both the object path and the string path (some embed providers) still work, and added a comment noting why.

But if we're inside the try block and we only care to handle the object, then should we just skip the string parse flow altogether?

Something like...

try {
  if ( message.action === 'ready' ) {
    return message as SandboxMessage;
  }
} catch {}

- Simplify parseSandBoxMessage to lean on the try block.
- Collapse the ready-message handling in the iframe to a single object path.
- Use NodeList.forEach and a WeakSet so nested iframe load listeners are
  attached only once instead of on every DOM mutation.
- Revert useLayoutEffect back to useEffect; the postMessage handshake already
  resolves the race regardless of effect timing.
- Replace the source-string-matching test with behavioral tests that verify
  the parent resizes on a resize message and ignores foreign sources.
@itzmekhokan
itzmekhokan requested a review from aduth June 19, 2026 04:59
@aduth

aduth commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

I was having some difficulty trying to test this. Specifically, the testing instructions work as intended on trunk, so I don't think it's representative of the failing scenario. Judging by the issue, it seems like this is more about specific embeds. I tried a few different embeds (Spotify, Bandcamp as in the original #78576), neither of which really demonstrate the fix (Spotify works before and after, Bandcamp works neither before nor after). Is there one that you've been using to test this fix in isolation?

It also has me wondering: Is the "two-way messaging" actually a necessary part of the fix? Or is the issue only due to how nested embeds may load dynamically and we need to send a second message after the initial resize when those nested frames finish loading? The latter would be a simpler fix if we could limit it to that.

The branch could also use a rebase/refresh at this point to resolve the conflicts. Apologies for the delays in getting feedback here since the pull request was opened.

@aduth

aduth commented Jun 23, 2026

Copy link
Copy Markdown
Member

Bandcamp works neither before nor after

Not something to address here, but this feels like a rather unfortunate side-effect of #77212 (cc @alecgeatches). It would be worth looking into some of these incompatibilities to see if there's any options to improve support without regressing on the hardened security introduced there.

@cbravobernal cbravobernal moved this from 🔎 Needs Review to 🦵 Punted to 7.1 in WordPress 7.0 Editor Tasks Jul 7, 2026
@mirmpro

mirmpro commented Jul 25, 2026

Copy link
Copy Markdown

== Test Report
Patch tested: https://github.com/WordPress/wordpress-develop/pull/78576

=== Environment

  • WordPress: 7.1-beta3
  • Subdirectory: No
  • PHP: 8.4.16
  • Server: nginx/1.26.1
  • Database: mysqli (Server: 8.0.35 / Client: mysqlnd 8.4.16)
  • Browser: Chrome 150.0.0.0
  • OS: Windows 10/11
  • Theme: Twenty Twenty-Five 1.5
  • MU Plugins: None activated
  • Plugins:
    • Code Snippets 3.9.6
    • Test Reports 1.3.0
    • WordPress Beta Tester 4.0.0
    • WP Mail Logging 1.16.0

=== Steps taken

  1. Created a new post in the WordPress block editor and inserted a Custom HTML block.
  2. Added HTML content inside the block, saved the post, and reopened the editor to verify layout and sizing.
  3. ✅ Patch is solving the problem

=== Expected result

  • The Custom HTML block preview should render immediately with the correct height on initial load and updates without collapsing to zero height.

=== Additional Notes

=== Screenshots/Screencast with results

  • N/A

=== Support Content

  • N/A

@nazmulasif

Copy link
Copy Markdown

== Patch Test Report
Patch tested: https://github.com/WordPress/wordpress-develop/pull/78576

=== Environment

  • WordPress: 7.1-beta3
  • Subdirectory: No
  • PHP: 8.4
  • Server: nginx/1.26.1
  • Database: mysqli (Server: 8.0.35 / Client: mysqlnd 8.4.16)
  • Browser: Chrome 150.0.0.0
  • OS: Windows 11
  • Theme: Twenty Twenty-Five 1.5
  • MU Plugins: None activated
  • Plugins:
    • Test Reports 1.3.0

=== Steps taken

  1. Created a new post in the block editor on WordPress 7.1-beta3 with pull request Custom HTML block disappears #78576 applied.
  2. Inserted a Custom HTML block and added sample markup (<p>Hello World</p>), then clicked update.
  3. Verified that the block preview rendered correctly right away without requiring a page refresh.
  4. Saved the post, closed the editor, and reopened the post to confirm the preview appeared immediately on the first load.
  5. Added a nested iframe inside a Custom HTML block and verified that the preview area calculated and adjusted its height correctly.
  6. ✅ Patch is solving the problem

=== Expected result

  • The Custom HTML block preview iframe should render with the correct height on initial load, after updates, and when reopening a saved post without remaining stuck at zero height.

=== Actual Results

  • The patch works as expected. The Custom HTML preview rendered cleanly and sized properly across all test scenarios without collapsing.

=== Additional Notes

=== Screenshots/Screencast with results

  • Yes

=== Support Content

  • Yes
image (18)

@github-project-automation github-project-automation Bot moved this to 🔎 Needs Review in WordPress 7.2 Editor Tasks Aug 13, 2026
@t-hamano t-hamano removed the Backport to WP Minor Release Pull request that needs to be backported to a WordPress minor release label Aug 26, 2026
@aduth aduth mentioned this pull request Sep 8, 2026
4 of 6 tasks
@t-hamano

t-hamano commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Thanks for working on this, @itzmekhokan!

On trunk, the Custom HTML block no longer renders its content in a SandBox iframe in the editor canvas, and #84150 (which closed #78576) added a marker for blocks that render nothing. So I think this issue is resolved, and I'm going to close this PR. If you still see a sizing issue in the "Edit HTML" modal preview, feel free to open a new issue with steps to reproduce.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Block] HTML Affects the the HTML Block [Package] Components /packages/components [Type] Bug An existing feature does not function as intended

Projects

Development

Successfully merging this pull request may close these issues.

Custom HTML block disappears

8 participants