WWW FAQs: How can a link in one window send another window or frame to a new page?


2005-08-13: It's not difficult to arrange things so that a link opens a new browser window with the characteristics you want. See How do I open a new window of a certain size? Once we have more than one window (or frame), it's not uncommon to want links in the first window or frame to control what is displayed in the second. We can do that by giving names to our windows and using the target attribute of the <a> element when writing our links. We set the target attribute to the name of the window the link should be followed in:

<a href="somewhere.html" target="otherwindow">Click Here</a>

If there is currently no window open with the name otherwindow, a new window will open. Future clicks on links with the target attribute otherwindow will reuse that window.

Note that all of these techniques work just as well for frames as they do for windows. Just use the name of the frame you want to follow the link in as the target.
But what if we want to take control of a window that we didn't create? For instance, if the user launches a web browser and types in www.example.com, and our home page opens a second window, how can that second window control the first if we didn't create it in the first place?

We can solve the problem with JavaScript code like this:

<script> window.name = "otherwindow"; </script>

Including this code in the <head> element of the www.example.com home page will take care of renaming the window.

In this case, we've used the name otherwindow. But when you use this technique in practice, we recommend using a name that is fairly unique to your site, such as examplecom_otherwindow. Window names like help or main can lead to confusion when the user navigates to other sites which unexpectedly reuse that window in strange ways.

Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.

Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!