How to retrieve data from JavaScript message event listener

I need help getting the message data from a JavaScript event listener. I’m working with a booking widget and trying to capture specific events, but I can’t seem to access the message content properly.

Here’s my current code:

// booking widget event handler
function isBookingEvent(event) {
  return event.data.type &&
         event.data.type.indexOf('booking') === 0;
};

window.addEventListener(
  'message',
  function(event) {
    if (isBookingEvent(event)) {
      console.log(event.data);
      if(event.data == 'booking.form_submitted') {
        handleSubmission();
      }
    }
  }
);

I’ve attempted different ways to check the message content like if(event.data.type == 'booking.form_submitted') and if(event.data.payload == 'booking.form_submitted') but none of these approaches work. The event listener fires but the condition never matches. What’s the correct way to access and compare the message content?

you’re comparing the whole event.data object to a string, which won’t work. add some debugging to see what’s actually coming through:

console.log('type:', typeof event.data);
console.log('actual value:', event.data.type);

i’m betting you need event.data.type === 'booking.form_submitted' instead of just event.data. also check for extra whitespace or different casing in the message type that might be causing the mismatch.

Your issue is probably how you’re comparing the event data. You’re checking event.data == 'booking.form_submitted' but looking at your isBookingEvent function, event.data seems to be an object with a type property, not a string.

First, log the whole event to see what you’re actually getting:

console.log('Full event:', event)
console.log('Event data structure:', JSON.stringify(event.data))

This’ll show you exactly what properties exist. If the message type lives in event.data.type, then you need if(event.data.type === 'booking.form_submitted') instead.

Also switch to strict equality (===) instead of loose (==) - avoids weird type conversion bugs.

One more thing: double-check that the sending side is actually posting the message format you expect. Cross-origin messaging can be finicky with data formatting.

Your problem’s probably with how you’re accessing and comparing event.data. Since you’re using isBookingEvent, event.data is likely an object with a type property. Log the full event first to see what you’re working with:

console.log('Event data:', event.data);

Once you confirm the structure, don’t compare event.data directly. Use event.data.type instead: if(event.data.type === 'booking.form_submitted'). Also make sure your event listener’s set up before the booking widget tries sending messages - you might miss early ones otherwise.

This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.