prevent parent DOM manipulation for a child iframe script
I have a page containing another page on the same domain inside a frame. Is it possible to prevent that a script in the framed page can manipulate the top pag开发者_JS百科e DOM (for example adding an element or a script)?
You could experiment with getting rid of "dangerous" functions but saving anonymous references to them something like..
(function(){
var hiddenrefs = {};
hiddenrefs.dGetElementById = document.getElementById;
document.getElementById = null;
})();
and so on. However, this would be a very tedious job and bound to fail anyway. If this is an attempt to let users run Javascript in a controlled environment inside an iframe, this is a misguided form of security. The iframe could just issue top.location = "http://www.myevilpage.com"
in which case it's game over for you anyway. (This is true even with a different domain. The iframe can still redirect the user and all sorts of nasty stuff, even if it strictly speaking can't access the parent's DOM.) Letting users run JS code is never ever safe without filtering the source code for malicious code, and even with filtering it's fairly unsafe because it's mostly easy to bypass the filtering. Many have tried and many have failed. I'd recommend not letting users run Javascript, ever.
The best solution is probably to use the HTML5 sandbox attribute on the iframe, which (by default) explicitly disables both scripting and same-origin access to the parent DOM.
See http://msdn.microsoft.com/en-us/hh563496.aspx
精彩评论