Using postMessage in WordPress (nothing to do with the Customiser)

I am trying to listen for a postMessage from an iFrame (triggered by user interaction with the iFrame) from within some javascript in a WordPress template.

The iFrame sends the postMessage in a simple fashion:

targetWindow = window.parent;

if (user interacts in a certain way) {
targetWindow.postMessage(“hello”, “*”);
}

I have tried various rewrites of the listener code, but all look something like (in the simplest form):

$(document).ready(function () {
window.addEventListener(‘message’, function (event) {
console.log(event.data);
});
});

I am using a Homestead for my dev environment, and have both WordPress and a basic HTML environments set up.

In the HTML environment, I can interact with the iFrame and see the postMessage hello being logged to the console.

In the WordPress environment, using exactly the same code, with the JS enqueued against the footer in the normal way, I get nothing, not even an error.

I’ve had a look around both here and some general googling, and I can’t find anything outside of the theme-customiser. I don’t know if WordPress somehow hijacks the postMessage for it’s theme customiser, and that’s why I can’t see anything, or if I need to go about listening for and catching the message in another way.

Thanks.

Read more here:: Using postMessage in WordPress (nothing to do with the Customiser)

Leave a Reply

Your email address will not be published. Required fields are marked *