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
<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.hotelanswer.com" marginwidth="0" frameborder="0" height="180" scrolling="no" width="210"></iframe><br>
</body>
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/
var iframes = document.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) {
iframes[i].parentNode.removeChild(iframes[i]);
}
Pure Javascript code:
document.querySelectorAll('iframe').forEach(
function(elem){
elem.parentNode.removeChild(elem);
});
You didn't mention why you need to remove iframes in the document.
I do it in order to prevent Clickjacking attack. But it will work in any cases.
You need this:
<style id="defendClickjack" type="text/css">body{display:none;}</style>
and then
<script type="text/javascript">
if (self === top) {
var defendClickjack = document.getElementById("defendClickjack");
antiClickjack.parentNode.removeChild(defendClickjack);
}
else {
top.location = self.location;
}
</script>
You can find more information here:
https://www.owasp.org/index.php/Clickjacking
http://en.wikipedia.org/wiki/Clickjacking
Slight improvement here to Matt's original example if you want to only do it on mobile. For me, the use case was that I'm using a Vimeo embed on my site to create a video background. I needed to ditch the video on mobile for performance. This does the job.
$( document ).ready(function() {
let isMobile = window.matchMedia("only screen and (max-width:650px)").matches;
if (isMobile) {
var iframes = document.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) {
iframes[i].parentNode.removeChild(iframes[i]);
}
}
});
s.ermakovich's comment about code not working properly with more than one iframe is not 'wrong' but a bit misleading...and depends on the situation. My Vimeo iFrame had a child frame making requests that continued after DOM complete. Matt's code did destroy both.
In my case my 2nd iframe was a direct child of the parent. The code might not work if you have several iframes on a page that are not direct children of the same parent and you just copy and paste that code. In this case you need to be more specific:
If you have multiple iFrames on your page you can add specificity to your query selector. Your choice if you want to use querySelectorAll() or not based on the situation, but I see no reason why querySelector() can't be used either.
document.querySelector(".foo > bar iframe")
document.querySelector("foo bar > iframe")
If you have a grid of iframes, perhaps several embedded videos in a row perhaps
document.querySelectorAll("foo > .bar > iframe")
or maybe better from the same data source...
document.querySelectorAll("iframe[data-src]")
Someone please correct me if I'm wrong somewhere
You should put the iframe inside of a div element.
<div id="kk">
//your iframe
</div>
Then use jQuery to remove the iframe.
$('#kk').click(function(){
$(this).html("");
});
This is a possible solution.
Related
I am automating a process wherein I have to login to website and download only the CSV files from the different types of files.
My jQuery code is getting executed in the console but not getting executed after integrating with HTML. Please find the jQuery code below :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(window).on("load", function() {
$('.ibody tr').each(function(a, b) {
var count = 0;
var name = $('.cl', b).text();
if (name.indexOf(".CSV") !== -1 && name.indexOf("TAS") !== -1) {
var d = a - 9;
var hiddenIFrameID = 'hiddenDownloader' + count++;
var iframe = window.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
window.body.appendChild(iframe);
iframe.src = "https://www.shipper-ml.com/viewReports.do?ctrl=reportListForDownload&action=DownloadReport¶m=" + d;
}
});
});
</script>
</head>
<body></body>
</html>
EDIT: I was, indeed, off-base with this. Didn't read your code carefully.
leaving this here for historical purposes...
I might be completely off-base with my assumptions here, and apologize in advance if this is the case. That said, it really looks like you are trying to load a page inside an IFrame and use jQuery outside of the IFrame to read data from inside the IFrame.
Long story short: you cannot use jQuery (or any javascript, or, indeed, ANYTHING AT ALL, if the browsers are working as they should) to manipulate or read content that is inside an IFrame, from outside the IFrame, if that IFrame has a src tag.
You can only manipulate / read from iframe you have built from scratch by yourself. This is by design, and for an important security reason. If you want to use IFrame to display a page, you are severely restricted to only show the page to user as-is.
If my assumption was correct, you need to either:
Get your JavaScript embedded (nicely) into the page you are now loading in your IFrame or
Use an AJAX call to get the contents of that page into your current page's memory context. This will probably mean jumping through some hoops if you really want to use jQuery to find all the elements you want.
...or, you may be able to create an empty IFrame, put the content you got from the AJAX call into that IFrame along with your Javascript, and get it to work. maybe. Not sure about this one.
can you please try with this? replace your window.createElement with document.createElement .
$(document).ready(function() {
$('.ibody tr').each(function(a, b) {
var count = 0;
var name = $('.cl', b).text();
if (name.indexOf(".CSV") !== -1 && name.indexOf("TAS") !== -1) {
var d = a - 9;
var hiddenIFrameID = 'hiddenDownloader' + count++;
var iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = "https://www.shipper-ml.com/viewReports.do?ctrl=reportListForDownload&action=DownloadReport¶m=" + d;
}
});
})
<iframe id="id_description_iframe" class="rte-zone" height="200" frameborder="0" title="description">
<html>
<head></head>
<body class="frameBody">
test<br/>
</body>
</html>
</iframe>
What I want to get is:
test<br/>
The exact question is how to do it with pure JavaScript not with jQuery.
But I always use the solution that can be found in jQuery's source code.
It's just one line of native JavaScript.
For me it's the best, easy readable and even afaik the shortest way to get the iframes content.
First get your iframe
var iframe = document.getElementById('id_description_iframe');
// or
var iframe = document.querySelector('#id_description_iframe');
And then use jQuery's solution
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
It works even in the Internet Explorer which does this trick during the contentWindow property of the iframe object. Most other browsers uses the contentDocument property and that is the reason why we proof this property first in this OR condition. If it is not set try contentWindow.document.
Select elements in iframe
Then you can usually use getElementById() or even querySelectorAll() to select the DOM-Element from the iframeDocument:
if (!iframeDocument) {
throw "iframe couldn't be found in DOM.";
}
var iframeContent = iframeDocument.getElementById('frameBody');
// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');
Call functions in the iframe
Get just the window element from iframe to call some global functions, variables or whole libraries (e.g. jQuery):
var iframeWindow = iframe.contentWindow;
// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');
// or
iframeContent = iframeWindow.$('#frameBody');
// or even use any other global variable
iframeWindow.myVar = window.myVar;
// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);
Note
All this is possible if you observe the same-origin policy.
Using JQuery, try this:
$("#id_description_iframe").contents().find("body").html()
it works perfectly for me :
document.getElementById('iframe_id').contentWindow.document.body.innerHTML;
AFAIK, an Iframe cannot be used that way. You need to point its src attribute to another page.
Here's how to get its body content using plane old javascript. This works with both IE and Firefox.
function getFrameContents(){
var iFrame = document.getElementById('id_description_iframe');
var iFrameBody;
if ( iFrame.contentDocument )
{ // FF
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
}
else if ( iFrame.contentWindow )
{ // IE
iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
}
alert(iFrameBody.innerHTML);
}
use content in iframe with JS:
document.getElementById('id_iframe').contentWindow.document.write('content');
I think placing text inbetween the tags is reserved for browsers that cant handle iframes i.e...
<iframe src ="html_intro.asp" width="100%" height="300">
<p>Your browser does not support iframes.</p>
</iframe>
You use the 'src' attribute to set the source of the iframes html...
Hope that helps :)
Chalkey is correct, you need to use the src attribute to specify the page to be contained in the iframe. Providing you do this, and the document in the iframe is in the same domain as the parent document, you can use this:
var e = document.getElementById("id_description_iframe");
if(e != null) {
alert(e.contentWindow.document.body.innerHTML);
}
Obviously you can then do something useful with the contents instead of just putting them in an alert.
The following code is cross-browser compliant. It works in IE7, IE8, Fx 3, Safari, and Chrome, so no need to handle cross-browser issues. Did not test in IE6.
<iframe id="iframeId" name="iframeId">...</iframe>
<script type="text/javascript">
var iframeDoc;
if (window.frames && window.frames.iframeId &&
(iframeDoc = window.frames.iframeId.document)) {
var iframeBody = iframeDoc.body;
var ifromContent = iframeBody.innerHTML;
}
</script>
To get body content from javascript ,i have tried the following code:
var frameObj = document.getElementById('id_description_iframe');
var frameContent = frameObj.contentWindow.document.body.innerHTML;
where "id_description_iframe" is your iframe's id.
This code is working fine for me.
If you want to not just select the body of your iframe, but also insert some content to it, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution that no other answer provides.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
You can get the contents of the iframe body in one line of code:
document.getElementsByTagName('iframe')[0].contentWindow.document.body.innerText;
I have been having some issues figuring this out.
Page 1
<iframe id="block" src="page2.html" tag> </iframe>
I want to hover in the Iframe and trigger an event if the element that I am hovering has a certain tag.
$("*").hover(function(){
var attr = $(this).attr('name');
if (typeof attr !== typeof undefined && attr !== false) {
return; //do something
}
});
I have tried multiple things but they all seem to want something just a bit different, I understand the firing of a event from a parent class. I don't seem to get how to do this though. The result that I want:
I hover in the Iframe over an element that has tag
I get a response on the end of the Iframe that I can work with further
I feel like I got very close but I just need a little piece of connecting code, hopefully someone can explain what I need.
As long as you're on the same domain (you are) there is an easy way:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<iframe id="block" src="page.html" onload="test()"></iframe>
<script>
function test() {
var iframe = document.getElementById('block');
var doc = iframe.contentDocument || iframe.contentWindow.document;
var element = doc.getElementById('hover');
$(element).hover(function() {
element.append("It's working!\n");
});
}
</script>
I would like to write a greasemonkey script to disable a div on a certain page.
On any given load of the page I don't know where in the DOM the div will be but I know it's always called <div id = "alertPanel"> ....</div>
How would I go about disabling this div?
My intial thoughts were something along the lines of:
var myDivs= document.getElementsByTagName('div');
for (i=0; i<myDivs.length; i++)
{
if (myDivs[i].<get id property somehow> = "alertPanel")
myDivs[i].style.visibility = 'hidden';
}
but as you can tell I'm stuck at accessing the id property for an equality check.
Incidently, I'm using a text editor to write this - I guessing that a standard javascript editor would give an autocompletion list after typing in myDivs[i].
If it has an id, you can use document.getElementById:
var div = document.getElementById("alertPanel");
Then if it exists, you can either remove it (probably a bad idea) or hide it:
if (div) {
div.style.display = "none"; // Hides it
// Or
// div.parentNode.removeChild(div); // Removes it entirely
}
Update: Re your comment on another answer:
thanks for your answer. Does your statemt apply to a page with iframes too. The div in question is in an iframe. I've tried ypur solution and it didn't work unfortunately. maybe a link to the page will help: tennis.betfair.com the div i want to disable is the one with id: minigamesContainer
If the element is in an iframe, then you have to call getElementById on the document that's in the iframe, since iframes are separate windows and have separate documents. If you know the id of the iframe, you can use document.getElementById to get the iframe instance, and then use contentDocument to access its document, and then use getElementById on that to get the "minigamesContainer" element:
var iframe, div;
iframe = document.getElementById("the_iframe_id");
if (iframe) {
try {
div = iframe.contentDocument.getElementById("minigamesContainer");
if (div) {
div.style.display = "none";
}
}
catch (e) {
}
}
(The try/catch is there because of a potential security error accessing the content of the iframe; I don't know Greasemonkey well enough to know whether the SOP applies to it. I tend to assume it doesn't, but better safe...)
If you don't know the id of the iframe or if it doesn't have one, you can just loop through all of them by getting them with document.getElementsByTagName and then looping:
var iframes, index, iframe, div;
iframes = document.getElementsByTagName("iframe");
for (index = 0; index < iframes.length; ++index) {
iframe = iframes[index];
try {
div = iframe.contentDocument.getElementById("minigamesContainer");
if (div) {
div.style.display = "none";
break;
}
}
catch (e) {
}
}
References:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Applications APIs
In valid HTML you can have only element with certain ID. So:
document.getElementById('alertPanel').style.visiblity = 'hidden';
But if you still need to iterate all div's and check their ID's, then this should work:
if (myDivs[i].id == "alertPanel") myDivs[i].style.visibility = 'hidden';
<iframe id="id_description_iframe" class="rte-zone" height="200" frameborder="0" title="description">
<html>
<head></head>
<body class="frameBody">
test<br/>
</body>
</html>
</iframe>
What I want to get is:
test<br/>
The exact question is how to do it with pure JavaScript not with jQuery.
But I always use the solution that can be found in jQuery's source code.
It's just one line of native JavaScript.
For me it's the best, easy readable and even afaik the shortest way to get the iframes content.
First get your iframe
var iframe = document.getElementById('id_description_iframe');
// or
var iframe = document.querySelector('#id_description_iframe');
And then use jQuery's solution
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
It works even in the Internet Explorer which does this trick during the contentWindow property of the iframe object. Most other browsers uses the contentDocument property and that is the reason why we proof this property first in this OR condition. If it is not set try contentWindow.document.
Select elements in iframe
Then you can usually use getElementById() or even querySelectorAll() to select the DOM-Element from the iframeDocument:
if (!iframeDocument) {
throw "iframe couldn't be found in DOM.";
}
var iframeContent = iframeDocument.getElementById('frameBody');
// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');
Call functions in the iframe
Get just the window element from iframe to call some global functions, variables or whole libraries (e.g. jQuery):
var iframeWindow = iframe.contentWindow;
// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');
// or
iframeContent = iframeWindow.$('#frameBody');
// or even use any other global variable
iframeWindow.myVar = window.myVar;
// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);
Note
All this is possible if you observe the same-origin policy.
Using JQuery, try this:
$("#id_description_iframe").contents().find("body").html()
it works perfectly for me :
document.getElementById('iframe_id').contentWindow.document.body.innerHTML;
AFAIK, an Iframe cannot be used that way. You need to point its src attribute to another page.
Here's how to get its body content using plane old javascript. This works with both IE and Firefox.
function getFrameContents(){
var iFrame = document.getElementById('id_description_iframe');
var iFrameBody;
if ( iFrame.contentDocument )
{ // FF
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
}
else if ( iFrame.contentWindow )
{ // IE
iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
}
alert(iFrameBody.innerHTML);
}
use content in iframe with JS:
document.getElementById('id_iframe').contentWindow.document.write('content');
I think placing text inbetween the tags is reserved for browsers that cant handle iframes i.e...
<iframe src ="html_intro.asp" width="100%" height="300">
<p>Your browser does not support iframes.</p>
</iframe>
You use the 'src' attribute to set the source of the iframes html...
Hope that helps :)
Chalkey is correct, you need to use the src attribute to specify the page to be contained in the iframe. Providing you do this, and the document in the iframe is in the same domain as the parent document, you can use this:
var e = document.getElementById("id_description_iframe");
if(e != null) {
alert(e.contentWindow.document.body.innerHTML);
}
Obviously you can then do something useful with the contents instead of just putting them in an alert.
The following code is cross-browser compliant. It works in IE7, IE8, Fx 3, Safari, and Chrome, so no need to handle cross-browser issues. Did not test in IE6.
<iframe id="iframeId" name="iframeId">...</iframe>
<script type="text/javascript">
var iframeDoc;
if (window.frames && window.frames.iframeId &&
(iframeDoc = window.frames.iframeId.document)) {
var iframeBody = iframeDoc.body;
var ifromContent = iframeBody.innerHTML;
}
</script>
To get body content from javascript ,i have tried the following code:
var frameObj = document.getElementById('id_description_iframe');
var frameContent = frameObj.contentWindow.document.body.innerHTML;
where "id_description_iframe" is your iframe's id.
This code is working fine for me.
If you want to not just select the body of your iframe, but also insert some content to it, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution that no other answer provides.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
You can get the contents of the iframe body in one line of code:
document.getElementsByTagName('iframe')[0].contentWindow.document.body.innerText;