Nếu bạn tạo động nội dung của khung nội tuyến của bạn, tất cả các kịch bản/biến nạp sẽ bị rò rỉ từ một ghi khác. Do đó, giải pháp được cung cấp bởi @Eli để xóa phần tử dom sẽ không hoạt động.
Nói tóm lại:
Để làm sạch, quấn iframe của bạn thành một phần tử div và thay thế nội dung dom của nó.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="wrapper">
<iframe id="test"></iframe>
</div>
</body>
</html>
Để làm sạch:
var wrapper = document.getElementById('wrapper');
wrapper.innerHTML= "<iframe id='test'></iframe>";
Cụ thể: Demo rò rỉ kịch bản
Ví dụ về rò rỉ kịch bản giữa hai iframe viết (thử nghiệm với Chrome):
var iframe = document.getElementById('test');
// define variable 'a'
var content = "<html><body><script>var a=555;</script></body></html>";
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(content);
iframe.contentWindow.document.close();
// uncomment this to clean the iframe
//document.getElementById('wrapper').innerHTML= "<iframe id='test'></iframe>";
// write 'a' if defined
var content2 = "<html><body><div id='content'></div><script>document.getElementById('content').innerHTML=typeof a === 'undefined' ? 'undefined' : a;</script></body></html>";
var iframe2 = document.getElementById('test');
iframe2.contentWindow.document.open();
iframe2.contentWindow.document.write(content2);
iframe2.contentWindow.document.close();
Nếu bạn chạy mã này, bạn sẽ thấy đầu ra của iframe thứ hai là 555
mặc dù iframe đã được xác định trong iframe đầu tiên.
Nếu bạn bỏ ghi chú phần giữa, nó sẽ hoạt động như mong đợi.
câu hỏi liên quan: Avoiding memory leaks loading content into an iframe
bạn chỉ có thể xóa và tạo một iframe mới. –
'$ (" # frameID "). Attr (" src "," ")' hoạt động tốt cho tôi trên Firefox 11. Nếu bạn thực sự muốn một iframe trống, bạn cũng có thể thử đặt 'src' thành' about: blank' thay vì một chuỗi rỗng. –
@IlmariKaronen 'about: blank' works wonders !!! – TheVillageIdiot