Search code examples
javascriptwindowparent-child

Remove parentage form child window


I am dealing with an old developer's site and code.

There is a GLOBAL print function the guy wrote that basically senses for any new window that opens (from any method) and "href.match"es the domain name... the script then applies a print stylesheet if need be and fires window.print.

This is all done from a global script that is on every page and houses some other functions.

I am tired of writing cases for each page added that I want to escape this function. Also if I do write a NOT clause for the certain page, any subsequent page opened within the domain in the child window will then receive that print function.

Is there a way to "bust" the inheritance in this new window? Basically to make this window NOT the child of the parent that spawned it?

    addEvent(window, 'load', function () {
    var printBtn = document.getElementById('print-page');
    if (window.opener && window.opener.location.href.match('domainnamehere')) {
        var printCSS = document.createElement('link');
        var a = document.getElementsByTagName('a');
        printCSS.href = 'css/print.css'
        printCSS.setAttribute('type', 'text/css');
        printCSS.setAttribute('rel', 'stylesheet');
        document.getElementsByTagName('head')[0].appendChild(printCSS);

        for (var i = 0; i < a.length; i++) {
            a[i].href="";
            a[i].onclick = function () { return false; };
            a[i].style.cursor = "default";
        }

        window.print();
    } else if (printBtn){
        printBtn.onclick = function () {
            var printWindow = window.open(window.location, 'printwindow', 'resizable,width=800,height=800,scrollbars');

            return false;
        };
    }
});

Solution

  • The opener property is what gives access to the child window, so if you want to disconnect it all you have to do is set it to null. When doing this, I always copy it to another property before nullifying in case you need it for other reasons...

    if(bustInheritance) {
      window.oldOpener = window.opener;
      window.opener = null;
    }