wp.customize.Messenger() to send
postMessage data to or from the
iframe. See below for a minimal example.
Note: This isn’t about previewing custom theme options.
The WordPress Customizer is divided into two panes: the “Controls” pane where you configure options, and the “Preview” pane where you get a real-time preview of the changes you made in the Controls pane. The Preview pane is inside an
iframe, so if you want to send custom data (“messages”) back and forth between them, you need to use the
The Customizer is already doing that for previewing theme options, but there are lots of other use cases for sending messages between the frames, like listening for keyboard events in the Preview pane, and then responding to them in the Controls pane.
Writing your own
postMessage send/receive functions is fairly straightforward, but there are some security considerations to take into account, and the Customizer API already provides the
wp.customize.Messenger class that can do all of that for you, so it’s best to use that, rather than rolling your own solution.
Save this as
wp-content/mu-plugins/post-message-example.php, then browse to the Customizer and open the dev tools console. Then, click inside the Preview frame, and start pressing keys. You should see the events being logged to the console.