Is there a way to prevent an iframe from redirecti

2019-03-23 08:37发布

问题:

So I've read about the HTML5 sandbox property and I understand that if I want to prevent an iframe redirect its parent window I can use the sandbox property leaving allow-top-navigation out. However when this is done, if the iframe was originally relying on top level redirection, what happens in its place is that it redirects to a blank page, effectively breaking navigation.

Can I prevent the iframe from tinkering its parent window while still allowing "top level" redirects, only letting these work within the context of the iframe instead of being top level?

Edit: For context, I'm working with a third party and its page has a form with a target _top. If the iframe is sandboxed, upon submitting the form users get a blank page, if it's not sandboxed the entire page is redirected. I'm looking for something that would allow to submit the form and show the result within the iframe itself.

回答1:

With HTML5 the iframe sandbox attribute was added.

At the time of writing this works on Chrome, Safari, Firefox and recent versions of IE and Opera but does pretty much what you want:

Allows the iframe content to be treated as being from the same origin as the containing document

<iframe src="url" sandbox="allow-same-origin"></iframe>

Browser Compatibility


Some Useful links

  • w3schools for sandbox
  • developer.mozilla.org iframe
  • -


回答2:

You can use the onbeforeunload property and determine if you wan to redirect or not.

Here is the docs page for it

Basically what I would try is this:

  • Make a function that adds the sandbox attribute with everything, just leaving out the allow-top-navigation, to the iframe
  • Bind a function to the onbeforeunload property of the iframe that calls the function that adds the sandbox attribute (be sure not to return anything because a dialog will pop-up)

This should work because the request is made in the iframe first, and then we can prevent it from carrying over to our top level window.

Another thing you should check is if you maybe left out the allow-formsoption, which can cause what you are describing.

Please let me know if any of this worked.