Finding an Element outside of your current iframe

Sometimes you are working within an iframe and need to be able to check for an element outside of that frame. It sounds simple enough, and you are right. The following bit of code grabs an element outside of your current iframe:


if (typeof window.parent != "undefined"){
window.parent.document.getElementById("SOMEID");
}

Pretty simple!

Now, lets look at a use case where you might actually need to do something like this. We will use jQuery to grab all of the links outside of the iframe and set an onclick event that will stop the link from working:


$("A", window.parent.document).click(function(e, data) {
// "this" is now the A that was clicked
console.log($(this));
e.preventDefault();
});

Now, we couple that with some jQuery UI magic and we can create a nice modal dialog box to pop up when a user clicks and prompt them to make sure they want to navigate away from the current page.


$("A", window.parent.document).click(function(e, data) {
// prevent the link from redirecting the page
e.preventDefault();

// "this" is now the A that was clicked
var url = $(this).attr('href');

// create a modal dialog box to prompt the user from leaving the page
var dom = '<div><a href="javascript:void(0);" class="leave">Leave Page</a> OR ' +
'<a href="javascript: void(0)" class="stay">Stay</a></div>';

var modal = $(dom).dialog({
modal: true,
resizable: false,
draggable: false,
closeOnEscape: false,
dialogClass: "no-titlebar loading-bar dialog-emphasis",
width: width || 250,
minHeight: height || 50
});

// setup the actions for each of the links in the modal dialog
$(".leave", modal).click(function(ev, data){
window.parent.location.href = url;
);

$(".stay", modal).click(function(ev, data){
modal.dialog('close');
});
});

* The dom string is causing issues with the syntax highlighter, which is why its on multiple lines, it should all be on one line.

And there you have it, a modal dialog overlay preventing the page from being unloaded without user consent.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>