用javascript删除iframe

One*_*ion 12 html javascript regex iframe

我想删除文档中的iFrame标记.这是功能.但它似乎没有用.这是我的示例代码

<script>
function removeiframe() {
            alert("Hello Lovely World");
            var markup = document.body.innerHTML;

            var filtered=markup.replace(/(<iframe.*?>.*?<\/iframe>)/g,"");
            alert("he: " + markup);
//markup = Regex.Replace(markup, @"<script.*?/script>", "", RegexOptions.IgnoreCase);
//markup = Regex.Replace(markup, @"<iframe.*?/iframe>", "", RegexOptions.IgnoreCase);
markup = filtered;
document.body.innerHTML = markup + "<hr><hr>HELLO";
        }
</script>
<body onload="removeiframe()">

        <iframe marginheight="0" src="http://www.metalgearrisingguide.com" marginwidth="0" frameborder="0" height="180" scrolling="no" width="210"></iframe><br>
</body>
Run Code Online (Sandbox Code Playgroud)

Mat*_*ant 24

这是您可以运行的脚本,它将从文档中删除所有iframe.以下是这个工作的一个例子:http://jsfiddle.net/5hh9H/

var iframes = document.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) {
    iframes[i].parentNode.removeChild(iframes[i]);
}
Run Code Online (Sandbox Code Playgroud)


小智 8

纯 JavaScript 代码:

document.querySelectorAll('iframe').forEach(
  function(elem){
    elem.parentNode.removeChild(elem);
});
Run Code Online (Sandbox Code Playgroud)


小智 5

您没有提到为什么需要删除文档中的iframe。

我这样做是为了防止Clickjacking攻击。但这在任何情况下都有效。

你需要这个:

<style id="defendClickjack" type="text/css">body{display:none;}</style>
Run Code Online (Sandbox Code Playgroud)

然后

<script type="text/javascript">
    if (self === top) {
        var defendClickjack = document.getElementById("defendClickjack");
        antiClickjack.parentNode.removeChild(defendClickjack);
    }
    else {
        top.location = self.location;
    }
</script>
Run Code Online (Sandbox Code Playgroud)

您可以在这里找到更多信息: