Tutorial :How to open a new browser window AND run Javascript through a single user interaction?



Question:

I have an HTML page with a simple form.

When the user clicks "submit", I'd like a new window to open with the processed results of the form, AND to have the original page redirect somewhere else.

If I use a link with target="_blank", I can open the results window but not redirect the original page. If I use Javascript to try and open the new window and then redirect the current page, the opening of the new window gets blocked (at least by my Firefox's default popup blocker).

Is there any way to get both a new window and run some Javascript in the original page?

Thanks!


Solution:1

Firstly, you'll need to set the "target" of the form you're submitting to "_blank", then use the onsubmit event of the form to change the current location as follows:

<form action="formResults.html" method="post" onsubmit="document.location.href='redirectPage.html'" name="MyForm" target="_blank" id="MyForm">    <input type="submit" name="button" id="button" value="Submit" />    <input type="text" name="textfield" id="textfield" />  </form>  


Solution:2

You should be able to use something along the lines of

<script type="text/javascript">  function onSubmit() {       if(valid()) {           setTimeout(function() { document.location.href = 'blah' }, 100);           return true;       }       return false  }  </script>    <form onsubmit="return onSubmit();" target="_blank">  ...  


Solution:3

I had a similar problem with a PDF which was generated on the fly from a form. The form was first validated and then opened the pdf on the fly in a new window. as this PDf could be opened within the window it would not fire javascript code to the parent.

My solution was to place a setTimeout('gosomewhere()', 100); just before the 'return true;' in the validation script.

The timeout of 100 milliseconds should be sufficient for the browser to open the new window.

{      setTimeout('gosomewhere()', 100);      return true;  }  

Hope this will be useful for all who encounter such problems.


Solution:4

u can have function on parent page like

function gosomewhere()  {  location.href="somewhere.html";  }  

and on the popup window use this function on onload event of body call this function

function parentRedirect()  {  window.opener.gosomewhere();  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »