Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Update parent window after closing the window opened by window.open()

  Peter        2012-06-23 01:36:32       8,306        0    

Imagine we have a webpage which has a text field to let user enter a date. Usually, we may create a calendar window to ask the user to pick one date from the calendar window, when the date is picked, the calendar window will close and the date picked will be put into the text field. This way involves the window.open() method in JavaScript, and we may think how the opened window knows its parent window and then updates the parent window. I give a simple demo on this.

We have two pages, on is the page which will trigger to open a new browser window, the other one is the page displayed in the opened window.

//window.html
<a href="javascript:openWindow();">Open window</a>
<br />
<div id="testPanel"></div>
<script type="text/javascript" >
function openWindow(){
    window.open('newwindow.html');
}
</script>

The window.html page contains a link which when clicked will call the JavaScript openWindow() function, the openWindow() function will open a new page newwindow.html in a new browser window. Here I just show the body contents of the webpage.

The next page is newwindow.html

    <a href="javascript:closeWindow();">Close window</a>
   
    <script type="text/javascript">
    function closeWindow(){
        window.opener.document.getElementById("testPanel").innerHTML="Returned value";
        window.close();
    }
    alert(window.opener);
    </script>

This page has a single link which when clicked will call the closeWindow() function, the closeWindow() function will first update the window.html page and then close the window. Here window.opener is the page window.html which opens the newwindow.html, it is an Window object. So we can access the elements in that page by using the window's document object.

After closing the newwindow.html. a string 'Returned value' will show on the window.html page. This demo is similar to the situation I mentioned at the beginning of the article. This method can be used in many situations when you want to open a new window and ask users to make some choices and update the original window.

UPDATE  WINDOW.OPEN  JAVASCRIPT  RETURN VALUE 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.