File size: 1,002 Bytes
1e92f2d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | type MessageAction = 'checkoutCompleted' | 'checkoutFailed' | 'checkoutCancelled';
// Check whether the current window is in the popup.
export const isPopup = () =>
typeof window !== 'undefined' && window.opener && window.opener !== window;
function isValidHttpUrl( data: string ): boolean {
let url;
try {
url = new URL( data );
} catch ( error ) {
return false;
}
return url.protocol === 'http:' || url.protocol === 'https:';
}
// Send the message to the opener.
export const sendMessageToOpener = ( siteSlug: string, action: MessageAction ) => {
if ( ! isPopup() ) {
return false;
}
if ( ! siteSlug ) {
return false;
}
const targetOrigin = `https://${ siteSlug }`;
if ( ! isValidHttpUrl( targetOrigin ) ) {
return false;
}
try {
window.opener.postMessage( { action }, targetOrigin );
} catch ( error ) {
// eslint-disable-next-line no-console
console.error( `Sending action '${ action }' to window.opener failed: ${ error }` );
return false;
}
return true;
};
|