Intercept iframe trying to redirect a parent page

I have an iFrame which contains a content that I cannot control. In some cases this iFrame redirects the top window which I want to prevent. Ideally I want to intercept this redirect, retrieve the redirect URL, and then redirect the top page to a different URL.

I’ve tried to use window beforeunload event, but it also adds a popup about “are you sure you want to leave a site” which I also want to avoid.

Also tried to use “sandbox” but it blocks redirect completely and I haven’t found a way to react on the redirection attempt in that case.

My current code as simple as that:

<iframe
  src="my embed url"
/>