javascriptiframe

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"
/>

EDIT: the full story if someone thinks I'm doing something shady. We use Figma as a 3rd party tool for making interactive prototype. They provide a specific URL for embedding purposes. In prototype that we made some buttons should redirect user to a different page. Unfortunately, Figma instead of just redirecting, firstly redirect the whole site to their URL with their custom warning regarding leaving a site. Numerous people reported that as bug, and asked them to fix this behaviour as it makes embed prototypes hardly useful. They didn't make any actions so far. As we already invested a lot of time into making this prototype before we learned about this forced warning window, I'm trying to find a workaround.


Solution

  • Over the years access to the location object in the browser has become more and more restrictive and although you are trying to do this for a good reason, the ever growing threats from third party components on the web mean the majority of reasons for wanting to this are increasingly malign, which has lead to cross origin access to locations being blocked.

    That said Figma could be doing this either via top.location.href or parent.location.href, if it is the latter then nesting the Figma iframe inside another iframe and then using onload to detect the outer iframe changing would work. However, if they went the top route you're basically out of luck on this these days for doing anything in the browser.