Html 使用 javascript 删除 iframe
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15103552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove iframe with javascript
提问by OneNation
I am trying to remove iFrame tags in my documents. This is the function. But it don't seem to work. Here is my sample code
我正在尝试删除文档中的 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>
回答by MattDiamant
Here's a script you can run that will remove all the iframes from your document. Here's an example of this working: http://jsfiddle.net/5hh9H/
这是您可以运行的脚本,该脚本将从您的文档中删除所有 iframe。这是这个工作的一个例子:http: //jsfiddle.net/5hh9H/
var iframes = document.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) {
iframes[i].parentNode.removeChild(iframes[i]);
}
回答by Georgii Gonchar
You didn't mention why you need to remove iframes in the document.
您没有提到为什么需要删除文档中的 iframe。
I do it in order to prevent ClickHymaning attack. But it will work in any cases.
我这样做是为了防止点击劫持攻击。但它在任何情况下都有效。
You need this:
你需要这个:
<style id="defendClickHyman" type="text/css">body{display:none;}</style>
and then
进而
<script type="text/javascript">
if (self === top) {
var defendClickHyman = document.getElementById("defendClickHyman");
antiClickHyman.parentNode.removeChild(defendClickHyman);
}
else {
top.location = self.location;
}
</script>
You can find more information here:
您可以在这里找到更多信息:
回答by user613826
Pure Javascript code:
纯Javascript代码:
document.querySelectorAll('iframe').forEach(
function(elem){
elem.parentNode.removeChild(elem);
});
回答by Leo
You should put the iframe inside of a div element.
您应该将 iframe 放在 div 元素内。
<div id="kk">
//your iframe
</div>
Then use jQuery to remove the iframe.
然后使用jQuery删除iframe。
$('#kk').click(function(){
$(this).html("");
});
This is a possible solution.
这是一个可能的解决方案。