Using javascript to read and write 'parent.location.href', in iframed page when cross domain

For some reason, we want to check if the page is in a iframe

And even more, we want to redirect the parent page to the current page, when it's in iframe.

So I did these two test:

Test Cases

  1. Readable of parent.location.href
  2. Writable of parent.location.href

Test Code

    
<script type="text/javascript">
    try {
        var local = location.href;
        var par = typeof(window.parent) != 'undefined' ? window.parent : null;
        if (par && par != window) {
            /*case 1: readable of parent.location.href*/
            //alert(par.location.href);
            //alert(par.location);
            /**
             * IE and Firefox raise an error
             * but Chrome returned 'undefined'
             * so "alert(par.location)" is the better way to test if the page is in iframe
             */

            /*case 2: writable of parent.location.href*/
            /*
            setTimeout(function(){
                par.location.href = local;
            }, 1000);
            */
            /**
             * in IE, Firefox and Chrome, parent.location.href is writable
             */
        }
    }catch(e) {
        alert('I\'m in iframe!');
    }
</script>
    

Test Result

Case 1: Readable of parent.location.href

Case 2: Writable of parent.location.href

<<Back home  Naked(no css) site by Lagtan#gmail.com.