| 1 |
import getCurrentFormUrlData from '@givewp/forms/app/utilities/getCurrentFormUrlData'; |
| 2 |
|
| 3 |
/** |
| 4 |
* Navigate the top-level window. A cross-origin embed cannot always navigate |
| 5 |
* window.top directly, so fall back to asking the parent page to navigate via |
| 6 |
* postMessage. The payload is only a URL; the receiving embed script is |
| 7 |
* responsible for validating it before navigating. |
| 8 |
* |
| 9 |
* The message is addressed to the host page's origin, taken from the |
| 10 |
* origin-url the embed script passed. The URL can carry a gateway approval |
| 11 |
* token or a receipt key, so it is not broadcast to whatever page happens to |
| 12 |
* frame the form. Without a usable origin the message is not sent. |
| 13 |
* |
| 14 |
* @since 4.17.0 |
| 15 |
*/ |
| 16 |
export default function navigateTop(url: string | URL): void { |
| 17 |
try { |
| 18 |
window.top.location.assign(url.toString()); |
| 19 |
} catch (e) { |
| 20 |
const targetOrigin = getHostOrigin(); |
| 21 |
|
| 22 |
if (targetOrigin) { |
| 23 |
window.parent.postMessage({type: 'givewp-navigate', url: url.toString()}, targetOrigin); |
| 24 |
} |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
function getHostOrigin(): string | null { |
| 29 |
try { |
| 30 |
const origin = new URL(getCurrentFormUrlData().originUrl).origin; |
| 31 |
|
| 32 |
return origin === 'null' ? null : origin; |
| 33 |
} catch (e) { |
| 34 |
return null; |
| 35 |
} |
| 36 |
} |
| 37 |
|