ASP.NET: Displaying a Second Window with JavaScript

Posted Mon, Jan 25 2010 9:34 by Deborah Kurata

In your ASP.NET application, you may want to allow a user to view some additional information without leaving the page that they are on. For example, you may want to display the current window and show some help text in a new window. Or you may want to display the concert ticket order page and allow the user to view the seating chart for the arena in a new window.

Though you can display a new window with HTML, doing it with JavaScript gives you more control over the window. To create a window with JavaScript, use the following code:

In JavaScript :

<script type="text/javascript">
<!--
   var winNew
   function OpenWindow(sURL,sName)
   {
      winNew = window.open(sURL,sName);
   }
-->
</script>

With JavaScript, you have control over the location and size of the window and whether to include the toolbar, location, scrollbars, and so on. Add the desired attributes to the open command to achieve your desired look:

In JavaScript :

winNew = window.open(sURL, sName,
  "toolbar=no, location=no, scrollbars=yes, width=600, height=300,
   top=400, left=300");

Notice that all of window attributes are in one string parameter.

To link to a new window, call the OpenWindow function in the a (anchor) element of your HTML as follows:

In HTML:

<a href="BLOCKED SCRIPTOpenWindow('CourseList.htm','CourseList');">
    View a list of our courses
</a>

To be a good citizen, close the new window when you no longer need it. Here is a function that closes the window:

In JavaScript :

function CloseWindow()
{
   if (winNew && !winNew.closed)
   {
      winNew.close();
   }
}

This code only closes the window if a new window exists and it is not already closed. This type of coding prevents errors in your JavaScript.

You may want to call this function from a button that the user can select, or from the unload event for the page so the new window is closed when the user leaves the page:

In HTML:

<body onunload="CloseWindow()">

Use this technique any time you want to open a second window from your HTML page.

(Based on an except from "Doing Web Development: Client-Side Techniques".)

Enjoy!

Filed under: , , , ,

Comments

# re: ASP.NET: Displaying a Second Window with JavaScript

Wednesday, January 27, 2010 8:14 PM by JavascriptBank.com

very cool & good tip, thank you very much for sharing.

# ASP.NET notes

Monday, February 08, 2010 12:42 AM by A working programmer's mind

ASP.NET notes

# Javascript new Window?

Wednesday, December 01, 2010 2:00 PM by Copious-Systems

Someone referenced this post to answer question "Javascript new Window?"...

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: