问题
Suppose http://a.com/foo contains <iframe src="http://b.com/bar">
Sometimes b.com/bar will break out of its frame: the top-level window will redirect away from a.com/foo into b.com/bar. I don't know how b.com is doing this.
I thought it wasn't possible for a cross-domain iframe to interfere with the parent unless the parent cooperates via postMessage. Is changing the window location exempt from this?
If that is what's happening, how can a.com prevent this redirect? I control a.com but cannot modify b.com.
If that's not what's happening, how can I find out what b.com is doing to achieve the redirect?
It would be acceptable to force b.com to load itself into a new window, or sabotage its access to the top or parent objects. Other degradations of b.com's behaviour may be acceptable.
回答1:
Parent can use sandbox attribute on iframe:
http://www.w3schools.com/TAgs/att_iframe_sandbox.asp
Then iframe will no longer be able to redirect parent.
回答2:
What may be happening is a link inside b.com has the attribute Target='_parent'. This would make the window/iframe parent update.
If you control b.com - ensure all your targets are _self.
回答3:
that's called 'frame busting'. Supposedly there are techniques to stop that ( http://seclab.stanford.edu/websec/framebusting/index.php ).
Maybe instead of an iframe you could use ajax or similar to load the frame's content into your page?
回答4:
An ajax solution could work if I create a.com/proxy.php which will use cURL to fetch b.com.
Pros:
- can change or remove any script
- can adjust b.com content (preview mode)
- can get around cross-domain iframe restrictions
Cons:
- cookies/sessions on b.com won't be available
- b.com may require scripts to create its content
- burden of bandwidth
- coding effort to make hrefs work
来源:https://stackoverflow.com/questions/9947026/prevent-iframe-from-changing-parent-location