--- title: window.open slug: Web/API/Window/open tags: - DOM - Dokumentacja_Gecko_DOM - Gecko - Strony_wymagające_dopracowania - Wszystkie_kategorie translation_of: Web/API/Window/open ---
{{ ApiRef() }}
Tworzy nowe okno przeglądarki i wczytuje do niego wskazany zasób.
referencjaDoObiektuOkna = window.open(strUrl, strNazwaOkna [, strCechyOkna]);
referencjaDoObiektuOkna
null
. Referencje taką dobrze jest przechowywać w zmiennej globalnej. Możesz wtedy użyć jej do do pobrania właściwości nowego okna lub wywołania jego metod - pod warunkiem, że zależność między głównym a nowym oknem spełnia Zasadę tego samego pochodzenia - wymaganą ze względów bezpieczeństwa.strUrl
strNazwaOkna
target
elementu <a>
lub <form>
. Nazwa nie powinna zawierać spacji. strNazwaOkna nie określa tytułu nowego okna.strCechyOkna
Metoda open()
tworzy nowe okno przeglądarki, podobnie jak przy wybraniu polecenia Nowe okno w menu Plik. Parametr strUrl określa URL, który ma zostać pobrany i załadowany w nowym oknie. Jeśli strUrl jest pustym ciągiem, utworzone zostanie puste okno (URL about:blank
) z domyślnym zestawem pasków głównego okna.
Zauważ, że zdalny URL nie zostanie załadowany od razu. Po zakończeniu wykonywania window.open()
okno zawsze zawiera about:blank
. Faktyczne pobieranie z adresu URL jest opóźniane do momentu zakończenia wykonywania bieżącego bloku skryptu. Tworzenie okna i ładowanie wskazanego zasobu odbywają się asynchronicznie.
<script type="text/javascript"> /* Deklaracja zmiennej globalnej, w której będzie przechowywana referencja do nowego okna */ var WindowObjectReference; function openRequestedPopup() { WindowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes"); } </script>
<script type="text/javascript"> var WindowObjectReference; // zmienna globalna function openRequestedPopup() { WindowObjectReference = window.open("http://www.domainname.ext/path/ImageFile.png", "DescriptiveWindowName", "resizable=yes,scrollbars=yes,status=yes"); } </script>
Jeśli istnieje już okno o tej samej nazwie strWindowName, to zamiast otwierania nowego okna w istniejącym oknie zostanie załadowany URL strUrl. W takim wypadku wartością zwracaną jest referencja do istniejącego okna, a parametr strWindowFeatures jest ignorowany. Wywołanie metody z pustym ciągiem jako strUrl to sposób uzyskania referencji do otwartego okna jeśli znana jest jego nazwa. Zawartość tego okna nie zostanie zmieniona. Jeśli chcesz otwierać nowe okno przy każdym wywołaniu window.open()
, podaj specjalną wartość _blank jako parametr strWindowName.
strWindowFeatures to opcjonalny ciąg znaków z rozdzieloną przecinkami listą żądanych cech nowego okna. Po otwarciu okna nie możesz zmienić jego funkcjonalności czy pasków za pomocą JavaScriptu. Jeśli strWindowName nie określa istniejącego okna i jeśli nie podasz parametru strWindowFeatures (lub będzie on tylko pustym ciągiem znaków), w nowym oknie znajdize się domyślny zestaw pasków głównego okna.
Jeżeli zostanie użyty parametr strWindowFeatures, ale nie zostaną podane cechy określające rozmiar, wymiary okna będą takie same, jak wymiary ostatnio wyrenderowanego okna.
Jeśli zostanie podany parametr strWindowFeatures, ale bez definiowania cech określających pozycję, wtedy współrzędne lewego górnego rogu będą przesunięte o 22 piksele od miejsca, gdzie znajdował się róg ostatnio wyrenderowanego okna. Przesunięcie to jest implementowane przez producentów przeglądarek (w MSIE 6 SP2 wynosi ono 29 pikseli przy domyślnym motywie) - ma ono ułatwiać użytkownikom dostrzeżenie, że otwarto nowe okno. Jeśli ostatnio używane okno było zmaksymalizowane, przesunięcie o 22 piksele nie zostanie użyte - nowe okno także będzie zmaksymalizowane.
Jeśli podajesz strWindowFeatures, cechy, które nie zostaną określone, będą wyłączone lub usunięte (z wyjątkiem titlebar i close, które domyślnie ustawiane są na yes)>.
Porada: Jeśli podajesz parametr strWindowFeatures, zawrzyj tylko te cechy, które chcesz, by były włączone lub wyświetlane; pozostałe (poza titlebar i close) zostaną wyłączone.
outerHeight
zawiera w sobie wszystkie widoczne paski, poziomy pasek przewijania (jeśli jest widoczny) i obramowanie okna. Minimalna wymana wartość to 100.outerHeight=100
zmniejszy innerHeight
okna poniżej wymaganych 100 pikseli.outerWidth
zawiera w sobie pionowy pasek przewijania (jeśli jest widoczny) i obramowanie okna. Minimalna wymana wartość to 100.dom.disable_window_open_feature.menubar
about:config
lub w ich pliku user.js.dom.disable_window_open_feature.toolbar
about:config
or in their user.js file.dom.disable_window_open_feature.location
about:config
or in their user.js file.Note that MSIE 7 will force the presence of the Address Bar: "We think the address bar is also important for users to see in pop-up windows. A missing address bar creates a chance for a fraudster to forge an address of their own. To help thwart that, IE7 will show the address bar on all internet windows to help users see where they are." coming from Microsoft Internet Explorer Blog, Better Website Identification
dom.disable_window_open_feature.directories
about:config
or in their user.js file.Tip: For accessibility reasons, it is strongly recommended to set this feature always to yes.
dom.disable_window_open_feature.resizable
about:config
or in their user.js file.Tip: For accessibility reasons, it is strongly encouraged to set this feature always to yes.
dom.disable_window_open_feature.scrollbars
about:config
or in their user.js file.showModelessDialog()
method.UniversalBrowserWrite
privilege ({{ Bug(244965) }}). Without this privilege it is ignored.UniversalBrowserWrite
privilege ({{ Bug(180048) }}). Without this privilege, it is equivalent to dependent
.showModalDialog()
method.dialog
feature removes all icons (restore, minimize, maximize) from the window's titlebar, leaving only the close button. dialog=yes
. If minimizable
is set to yes, the new dialog window will have a minimize system command icon in the titlebar and it will be minimizable. Any non-dialog window is always minimizable and minimizable=no
will be ignored.fullscreen
always upsets users with large monitor screen or with dual monitor screen. Forcing fullscreen
onto other users is also extremely unpopular and is considered an outright rude attempt to impose web author's viewing preferences onto users.fullscreen
does not really work work in MSIE 6 SP2.The following features require the UniversalBrowserWrite
privilege, otherwise they will be ignored. Chrome scripts have this privilege automatically, others have to request it from the PrivilegeManager.
dom.disable_window_open_feature.titlebar
about:config
or in their user.js file.alwaysLowered
.dialog
feature set). close=no
will override minimizable=yes
.dom.disable_window_open_feature.close
about:config
or in their user.js file.The position and size feature elements require a number to be set. The toolbars and window functionalities can be set with a yes or no; you can use 1 instead of yes and 0 instead of no. The toolbar and functionality feature elements also accept the shorthand form: you can turn a feature on by simply listing the feature name in the strWindowFeatures string. If you supply the strWindowFeatures parameter, then the titlebar
and close
are still yes by default, but the other features which have a yes/no choice will be no by default and will be turned off.
Example:
<script type="text/javascript"> var WindowObjectReference; // global variable function openRequestedPopup() { WindowObjectReference = window.open("http://www.domainname.ext/path/ImgFile.png", "DescriptiveWindowName", "width=420,height=230,resizable,scrollbars=yes,status=1"); } </script>
In this example, the window will be resizable, it will render scrollbar(s) if needed, if the content overflows requested window dimensions and it will render the status bar. It will not render the menubar nor the location bar. Since the author knew about the size of the image (400 pixels wide and 200 pixels high), he added the margins applied to the root element in MSIE 6 which is 15 pixels for top margin, 15 pixels for the bottom margin, 10 pixels for the left margin and 10 pixels for the right margin.
<script type="text/javascript"> var WindowObjectReference = null; // global variable function openFFPromotionPopup() { if(WindowObjectReference == null || WindowObjectReference.closed) /* if the pointer to the window object in memory does not exist or if such pointer exists but the window was closed */ { WindowObjectReference = window.open("http://www.spreadfirefox.com/", "PromoteFirefoxWindowName", "resizable=yes,scrollbars=yes,status=yes"); /* then create it. The new window will be created and will be brought on top of any other window. */ } else { WindowObjectReference.focus(); /* else the window reference must exist and the window is not closed; therefore, we can bring it back on top of any other window with the focus() method. There would be no need to re-create the window or to reload the referenced resource. */ }; } </script> (...) <p><a href="http://www.spreadfirefox.com/" target="PromoteFirefoxWindowName" onclick="openFFPromotionPopup(); return false;" title="This link will create a new window or will re-use an already opened one">Promote Firefox adoption</a></p>
The above code solves a few usability problems related to links opening secondary window. The purpose of the return false
in the code is to cancel default action of the link: if the onclick event handler is executed, then there is no need to execute the default action of the link. But if javascript support is disabled or non-existent on the user's browser, then the onclick event handler is ignored and the browser loads the referenced resource in the target frame or window that has the name "PromoteFirefoxWindowName". If no frame nor window has the name "PromoteFirefoxWindowName", then the browser will create a new window and will name it "PromoteFirefoxWindowName".
More reading on the use of the target attribute:
HTML 4.01 Target attribute specifications
How do I create a link that opens a new window?
You can also parameterize the function to make it versatile, functional in more situations, therefore re-usable in scripts and webpages:
<script type="text/javascript"> var WindowObjectReference = null; // global variable function openRequestedPopup(strUrl, strWindowName) { if(WindowObjectReference == null || WindowObjectReference.closed) { WindowObjectReference = window.open(strUrl, strWindowName, "resizable=yes,scrollbars=yes,status=yes"); } else { WindowObjectReference.focus(); }; } </script"> (...) <p><a href="http://www.spreadfirefox.com/" target="PromoteFirefoxWindow" onclick="openRequestedPopup(this.href, this.target); return false;" title="This link will create a new window or will re-use an already opened one">Promote Firefox adoption</a></p>
You can also make such function able to open only 1 secondary window and to reuse such single secondary window for other links in this manner:
<script type="text/javascript"> var WindowObjectReference = null; // global variable var PreviousUrl; /* global variable which will store the url currently in the secondary window */ function openRequestedSinglePopup(strUrl) { if(WindowObjectReference == null || WindowObjectReference.closed) { WindowObjectReference = window.open(strUrl, "SingleSecondaryWindowName", "resizable=yes,scrollbars=yes,status=yes"); } else if(previousUrl != strUrl) { WindowObjectReference = window.open(strUrl, "SingleSecondaryWindowName", "resizable=yes,scrollbars=yes,status=yes"); /* if the resource to load is different, then we load it in the already opened secondary window and then we bring such window back on top/in front of its parent window. */ WindowObjectReference.focus(); } else { WindowObjectReference.focus(); }; PreviousUrl = strUrl; /* explanation: we store the current url in order to compare url in the event of another call of this function. */ } </script> (...) <p><a href="http://www.spreadfirefox.com/" target="SingleSecondaryWindowName" onclick="openRequestedSinglePopup(this.href); return false;" title="This link will create a new window or will re-use an already opened one">Promote Firefox adoption</a></p> <p><a href="http://www.mozilla.org/support/firefox/faq" target="SingleSecondaryWindowName" onclick="openRequestedSinglePopup(this.href); return false;" title="This link will create a new window or will re-use an already opened one">Firefox FAQ</a></p>
"Scripts may not close windows that were not opened by script."
Otherwise the history of URLs visited during the browser session would be lost.about:config
. Since your users are the ones who are supposed to use such windows (and not you, being the web author), the best is to avoid interfering with their habits and preferences. We recommend to always set the resizability and scrollbars presence (if needed) to yes to insure accessibility to content and usability of windows. This is in the best interests of both the web author and the users.Edit/Preferences/Advanced/Scripts & Plug-ins/Allow Scripts to/ Move or resize existing windows
checkbox in Mozilla or
Tools/Options.../Content tab/Enable Javascript/Advanced button/Move or resize existing windows
checkbox in Firefox or by setting
dom.disable_window_move_resize
to true in the about:config
or by editing accordingly their user.js file.
Move or resize existing windows
checkbox. Moving and resizing a window remotely on the user's screen via script will very often annoy the users, will disorient the user, and will be wrong at best. The web author expects to have full control of (and can decide about) every position and size aspects of the users' browser window ... which is simply not true.window.open()
: it will be null if the window wasn't allowed to open. However, for most other popup blockers, there is no reliable way.window.open()
Generally speaking, it is preferable to avoid resorting to window.open() for several reasons:
If you want to offer to open a link in a new window, then follow tested and recommendable usability and accessibility guidelines:
<a href="javascript:window.open(...)" ...>
"javascript:" links break accessibility and usability of webpages in every browser.
Further reading:
<a href="#" onclick="window.open(...);">
Takie pseudo-linki ograniczają dostępność stron. Zawsze używaj rzeczywistych URLi jako wartości atrybutu href tak by w przypadku braku obsługi javascriptu lub gdy przeglądarka nie obsługuje otwierania odrębnych okien (jak w przypadku MS-Web TV, przeglądarek tekstowych, itp.), przeglądarka miała możliwość dostępu do zasobu zgodnie z domyślnym sposobem obsługi zasobów. Tak sformułowane linki kolidują także z dodatkowymi funkcjami przeglądarek obsługujących zakładki, np.: kliknięcie linku środkowym klawiszem myszy, kliknięcie linku z przytrzymanym klawiszem ctrl, naciśnięcie kombinacji ctrl+enter czy gesty myszą.
Identify links that will open new windows in a way that helps navigation for users by coding the title attribute of the link, by adding an icon at the end of the link or by coding the cursor accordingly.
The purpose is to warn users in advance of context changes to minimize confusion on the user's part: changing the current window or popping up new windows can be very disorienting to users (Back toolbar button is disabled).
"Users often don't notice that a new window has opened, especially if they are using a small monitor where the windows are maximized to fill up the screen. So a user who tries to return to the origin will be confused by a grayed out Back button."
quote from The Top Ten New Mistakes of Web Design: 2. Opening New Browser Windows, Jakob Nielsen, May 1999
When extreme changes in context are explicitly identified before they occur, then the users can determine if they wish to proceed or so they can be prepared for the change: not only they will not be confused or feel disoriented, but more experienced users can better decide how to open such links (in a new window or not, in the same window, in a new tab or not, in "background" or not).
References
Przykład ikon & kursorów "Nowego okna" | |||
![]() |
![]() |
![]() |
|
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
If javascript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the target attribute: e.g. some user agents which can not create new windows, like MS Web TV, will fetch the referenced resource and append it at the end of the current document. The goal and the idea is to try to provide - not impose - to the user a way to open the referenced resource, a mode of opening the link. Your code should not interfere with the features of the browser at the disposal of the user and your code should not interfere with the final decision resting with the user.
target="_blank"
Always provide a meaningful name to your target attribute and try to reuse such target attribute in your page so that a click on another link may load the referenced resource in an already created and rendered window (therefore speeding up the process for the user) and therefore justifying the reason (and user system resources, time spent) for creating a secondary window in the first place. Using a single target attribute value and reusing it in links is much more user resources friendly as it only creates one single secondary window which is recycled. On the other hand, using "_blank" as the target attribute value will create several new and unnamed windows on the user's desktop which can not be recycled, reused. In any case, if your code is well done, it will not interfere with the user's final choice but will rather merely offer him more choices, more ways to open links and more power to the tool he's using (a browser).
DOM Level 0. window.open() is not part of any W3C (World Wide Web Consortium) specification or technical recommendation.
In cases where left
and screenX
(and/or top
and screenY
) have conflicting values, then left
and top
have precedence over screenX
and screenY
respectively. If left
and screenX
(and/or top
and screenY
) are defined in the strWindowFeatures list, then left
(and/or top
) will be honored and rendered. In the following example the new window will be positioned at 100 pixels from the left side of the work area for applications of the user's operating system, not at 200 pixels.
<script type="text/javascript"> WindowObjectReference = window.open("http://news.bbc.co.uk/", "BBCWorldNewsWindowName", "left=100,screenX=200,resizable,scrollbars,status"); </script>
If left is set but top has no value and screenY has a value, then left and screenY will be the coordinate positioning values of the secondary window.
outerWidth has precedence over width and width has precedence over innerWidth. outerHeight has precedence over height and height has precedence over innerHeight. In the following example, Mozilla-browsers will create a new window with an outerWidth of 600 pixels wide and will ignore the request of a width of 500 pixels and will also ignore the request of an innerWidth of 400 pixels.
<script type="text/javascript"> WindowObjectReference = window.open("http://www.wwf.org/", "WWildlifeOrgWindowName", "outerWidth=600,width=500,innerWidth=400,resizable,scrollbars,status"); </script>
Requested position and requested dimension values in the strWindowFeatures list will not be honored and will be corrected if any of such requested value does not allow the entire browser window to be rendered within the work area for applications of the user's operating system. No part of the new window can be initially positioned offscreen. This is by default in all Mozilla-based browser releases.
MSIE 6 SP2 has a similar error correction mechanism but it is not activated by default in all security levels: a security setting can disable such error correction mechanism.
When content overflows window viewport dimensions, then scrollbar(s) (or some scrolling mechanism) are necessary to ensure that content can be accessed by users. Content can overflow window dimensions for several reasons which are outside the control of web authors:
You should assume that a large majority of users' browsers will have the status bar or that a large majority of users will want to force the status bar presence: best is to always set this feature to yes. Also, if you specifically request to remove the status bar, then Firefox users will not be able to view the Site Navigation toolbar if it is installed. In Mozilla and in Firefox, all windows with a status bar have a window resizing grippy at its right-most side. The status bar also provides info on http connection, hypertext resource location, download progress bar, encryption/secure connection info with SSL (Secure Socket Layer) connection (displaying a yellow padlock icon), internet/security zone icons, privacy policy/cookie icon, etc. Removing the status bar usually removes a lot of functionality, features and information considered useful (and sometimes vital) by the users.
In MSIE 6 for XP SP2: For windows opened using window.open():
"For windows opened using window.open():
Expect the status bar to be present, and code for it. The status bar will be on by default and is 20-25 pixels in height. (...)"
quote from Fine-Tune Your Web Site for Windows XP Service Pack 2, Browser Window Restrictions in XP SP2
"(...) windows that are created using the window.open() method can be called by scripts and used to spoof a user interface or desktop or to hide malicious information or activity by sizing the window so that the status bar is not visible.
Internet Explorer windows provide visible security information to the user to help them ascertain the source of the Web page and the security of the communication with that page. When these elements are not in view, the user might think they are on a more trusted page or interacting with a system process when they are actually interacting with a malicious host. (...)
Script-initiated windows will be displayed fully, with the Internet Explorer title bar and status bar. (...)
Script management of Internet Explorer status bar
Detailed description
Internet Explorer has been modified to not turn off the status bar for any windows. The status bar is always visible for all Internet Explorer windows. (...) Without this change, windows that are created using the window.open() method can be called by scripts and spoof a user interface or desktop or hide malicious information or activity by hiding important elements of the user interface from the user.
The status bar is a security feature of Internet Explorer windows that provides Internet Explorer security zone information to the user. This zone cannot be spoofed (...)"
quote from Changes to Functionality in Microsoft Windows XP Service Pack 2, Internet Explorer Window Restrictions
In MSIE 6 for XP SP2:
References:
JavaScript windows (tutorial) by Lasse Reichstein Nielsen
The perfect pop-up (tutorial) by Ian Lloyd
Popup windows and Firefox (interactive demos) by Gérard Talbot
Links Want To Be Links by Jukka K. Korpela
Links & JavaScript Living Together in Harmony by Jeff Howden