diff --git a/app/javascript/sdk/IFrameHelper.js b/app/javascript/sdk/IFrameHelper.js index 15c96d0f4..6496c198a 100644 --- a/app/javascript/sdk/IFrameHelper.js +++ b/app/javascript/sdk/IFrameHelper.js @@ -127,12 +127,27 @@ export const IFrameHelper = { window.onmessage = e => { if ( typeof e.data !== 'string' || - e.data.indexOf('chatwoot-widget:') !== 0 || - e.origin !== window.location.origin + e.data.indexOf('chatwoot-widget:') !== 0 ) { return; } + // Validate origin - allow messages from either: + // 1. The widget origin (widget -> parent communication) + // 2. The current page origin (same-origin messages) + const widgetOrigin = window.$chatwoot?.baseUrl + ? new URL(window.$chatwoot.baseUrl).origin + : null; + const parentOrigin = window.location.origin; + + const isValidOrigin = + e.origin === parentOrigin || + (widgetOrigin && e.origin === widgetOrigin); + + if (!isValidOrigin) { + return; + } + const message = JSON.parse(e.data.replace('chatwoot-widget:', '')); if (typeof IFrameHelper.events[message.event] === 'function') { IFrameHelper.events[message.event](message);