Jose Gallo Jose Gallo - 15 days ago 5
jQuery Question

Delete elements from iframe Jquery

I have a built-in iframe from a pools app webservice.
To add the iframe of a pool I add this code:

<script>
(function(d, s, id){
var js,
fjs = d.getElementsByTagName(s)[0],
p = (('https:' == d.location.protocol) ? 'https://' : 'http://'),
r = Math.floor(new Date().getTime() / 1000000);
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id; js.async=1;
js.src = p + "www.opinionstage.com/assets/loader.js?" + r;
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'os-widget-jssdk'));
</script>
<div id="18993" class="os_widget" data-path="...." data-comments="false" data-of="..."></div>


The structure of the html when the iframe loaded is:

<div id="18993" class="os_widget" style="..." ... >
<div class="os_widget_container os_widget_container0" style="..." >
<iframe " name="os_frame" style="..." src="... "> (no id)
<!DOCTYPE html>
...
<body>
...
<h1> </h1>
...
</body>
</html>
</iframe>
</div>
</div>


I want to hide or delete h1.

I have tried these with no success, even It doesn't allow me to add a id to iframe and of course I can't delete or hide h1:

a)

<script>
$(document).ready(function(){

var iFr = $('iframe');
iFr.load(function() {
iFr.attr('id','something');
iFr.contents().find('h1').css({'display' : 'none'});
//iFr.contents().find('h1').remove();
//$('something').contents().find('h1').hide();
});
});
</script>


b)

$(document).ready(function(){
var f = $("iframe");
f.load(function(){
f.find(' h1').css({'display' : 'none'});
//f.find('h1').hide();
//f.contents().find('h1').remove();
});
});
</script>


Any help, would be great and appreciated
Best
Jose

Answer

Due to security reasons you cannot access the content of an iFrame with its source coming form another domain, called the same-origin policy

There are some excpetions which are explained here.

The most reliable way to access html inside an iframe is, when you have access to the iframes source and/or domain.

A dirty way around that would be scraping the html from the other side and include it under your domain, but I definitely would not recommend doing this. You lose a lot of functionality and maybe miss crucial updates.

Comments