javascriptformsdomtarget

obtain reference to _blank target window on form submit


I have a form that is opening a new window on submit:

<form id="form-id" target="_blank">

I want to access the newly created window via javascript, without manually generating a unique name for target, and without resorting to an alternative method for opening the window.

It seems like there has to be an easy way of doing this but I wasn't able to find one that will work in my specific situation.


Solution

  • I'm not 100% sure this works in all browsers, but Firefox seems to set window.opener when a target attribute on an <a> or <form> causes a new window to open. Thus, you can go the other direction and find the original window from the new one (assuming you control the code there; if not, well I can't imagine you could do much with the window reference anyway).

    Of course one of the things the code in the new window can do is call a function in the old window, passing in its own window reference.

    Thus, specifically, if you have:

    <form action=whatever target=_blank>
    

    on the original page, then the page that ends up in the newly-opened window can do this:

    <head>
      <script>
        if (window.opener) {
          window.opener.announceWindow( window );
        }
      </script>
    

    That assumes announceWindow() is a function on the original page, something perhaps like:

    function announceWindow( win ) {
      // do stuff with "win", a newly-opened window
    }