Html windows open new windows

Open Link in a New Window

HTML attribute (valid in HTML5 now):

Inline JavaScript way:

Need front-end development training?

Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.

Need front-end development training?

Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.

Comments

I think some code might have gotten stripped there. Feel free to email me at [email protected] to fix.

Using the second approach opens the href in my current (parent) window too. i.e. my current window and new window both points to href value. I don’t want my parent window to be changed

My purpose was to open a link in new window,

i tried this, but my parent window(which has link) becomes blank when i click on the link.

It doesn’t work because it should be:

onclick=”window.open(this.href,’_blank’); return false;”

it doesnt though

Target-blank is not strict xhtml (it might be considered as behaviour that should not be placed in the mark-up) and it can make people angry when used on every link, especially the internal ones. But sometimes it can be useful, if there’s an external link among many internal links.
Personally I prefer to use CSS-Content to set a “(ext)” behind those links via auto-detection (attr).

I’d say it’s a bad practice. Because if I want to open link in new window, jsut press shift+mouse key. Or middle button (to open in new tab).

I’d say it’s the best practice to use target=”_blank”, because it simply works.
There are people who don’t know that you can press the middle mouse button or other shortcuts. Nobody will see it at the end. Why should I not break the rule on this point?

How with auto open in new windows?

sorry, i’m newbie in CSS 😀

Thanks! PDFs don’t seem to honor _blank.

hey Jason, for PDF’s use, target=”_new”

This snippet was very useful, thank you!

I think this article is misleading, it clearly states that target=”_blank” is invalid which isn’t true. It’s perfectly valid in both HTML5 and XHTML 1.0 Transitional. It’s only invalid in the strict DTD, but who uses that?
There’s no real reason not to use the target attribute, every browser supports it and will support it for the foreseeable future. And besides, why use JavaScript for something that the browser can do natively?

any benefit/downside to using html instead of JS or vice versa?

This sort of thing should br strongly discouraged. Only ever should a website had a teeny tiny sprinkle of target=»_blank» atop its icing. It is entirely the user’s choice as to whether they want another tab/window opened or not. It doesn’t matter if some users don’t know how to click with the middle-button; who are we to force new tabs upon those who do know how to open links in new tabs for the sake of the few ignorant users out there.

I’ve come across quite a few websites where links open in new tabs when they just shouldn’t and it’s frustrating, because I wanted the link to open in the current tab.

Leave target=»blank» alone unless you absolutely need it.

Читайте также:  Idt sound driver windows 10

Perfect! exactly what i’m looking for. thanks 🙂

There actually IS a need for links to open in a new windows… sometimes. I am designing and coding a site which collects data from users which requires them to upload files (images and pdf documents). The overall process involves employees filling out a form and then uploading receipt scans/images for reimbursement. This needs to be viewed by an admin intranet site within the office. I have a nice page displaying the claim in a cute form, easily printable if required, and links to the relevant file uploads.

I don’t want those links to take over the parent window. They are additional info to the data displayed in the parent window, so they are required to open in a new window or tab (based on browser preference settings) while leaving the parent windows alone. Frequently both windows will be examined and compared together. Hard to do if only one is open at a time!

And no, our accounts team are not IT knowledgeable enough to recognise how/when to choose to open a link in a new windows. They expect it done for them. And quite rightly so too.

Having said that, this is a rare case and I would not normally utilise this in any other way or for any other reason. It bothers me that using target=”_blank” is not acceptable in strict html5 mode. I always code my html/css/php to perfect strict acceptance levels. Well…. I did until now. This is the exception. :/

Открытие окон и методы window

Материал на этой странице устарел, поэтому скрыт из оглавления сайта.

Более новая информация по этой теме находится на странице https://learn.javascript.ru/popup-windows.

Всплывающее окно («попап» – от англ. Popup window) – один из старейших способов показать пользователю ещё один документ.

В этой статье мы рассмотрим открытие окон и ряд тонких моментов, которые с этим связаны.

…При запуске откроется новое окно с указанным URL.

Большинство браузеров по умолчанию создают новую вкладку вместо отдельного окна, но чуть далее мы увидим, что можно и «заказать» именно окно.

Блокировщик всплывающих окон

Рекламные попапы очень надоели посетителям, аж со времён 20-го века, поэтому современные браузеры всплывающие окна обычно блокируют. При этом пользователь, конечно, может изменить настройки блокирования для конкретного сайта.

Всплывающее окно блокируется в том случае, если вызов window.open произошёл не в результате действия посетителя.

Как же браузер понимает – посетитель вызвал открытие окна или нет?

Для этого при работе скрипта он хранит внутренний «флаг», который говорит – инициировал посетитель выполнение или нет. Например, при клике на кнопку весь код, который выполнится в результате, включая вложенные вызовы, будет иметь флаг «инициировано посетителем» и попапы при этом разрешены.

А если код был на странице и выполнился автоматически при её загрузке – у него этого флага не будет. Попапы будут заблокированы.

Полный синтаксис window.open

Функция возвращает ссылку на объект window нового окна, либо null , если окно было заблокировано браузером.

url URL для загрузки в новое окно. name Имя нового окна. Может быть использовано в параметре target в формах. Если позднее вызвать window.open() с тем же именем, то браузеры (кроме IE) заменяют существующее окно на новое. params Строка с конфигурацией для нового окна. Состоит из параметров, перечисленных через запятую. Пробелов в ней быть не должно.

Значения параметров params .

  1. Настройки расположения окна:

left/top (число)

Координаты верхнего левого угла относительно экрана. Ограничение: новое окно не может быть позиционировано за пределами экрана.

Ширина/высота нового окна. Минимальные значения ограничены, так что невозможно создать невидимое окно с нулевыми размерами.

Если координаты и размеры не указаны, то обычно браузер открывает не окно, а новую вкладку.

  1. Свойства окна:

menubar (yes/no) Скрыть или показать строку меню браузера. toolbar (yes/no) Показать или скрыть панель навигации браузера (кнопки назад, вперёд, обновить страницу и остальные) в новом окне. location (yes/no) Показать/скрыть поле URL-адреса в новом окне. По умолчанию Firefox и IE не позволяют скрывать строку адреса. status (yes/no) Показать или скрыть строку состояния. С другой стороны, браузер может в принудительном порядке показать строку состояния. resizable (yes/no) Позволяет отключить возможность изменять размеры нового окна. Значение no обычно неудобно посетителям. scrollbars (yes/no) Разрешает убрать полосы прокрутки для нового окна. Значение no обычно неудобно посетителям.

  1. Ещё есть небольшое количество не кросс-браузерных свойств, которые обычно не используются. Вы можете узнать о них в документации, например MDN: window.open.
Читайте также:  Warning windows x64 detected pio mode supported on windows x86 only что за ошибка

Браузер подходит к этим параметрам интеллектуально. Он может проигнорировать их часть или даже все, они скорее являются «пожеланиями», нежели «требованиями».

  • Если при вызове open указан только первый параметр, параметр отсутствует, то используются параметры по умолчанию. Обычно при этом будет открыто не окно, а вкладка, что зачастую более удобно.
  • Если указана строка с параметрами, но некоторые yes/no параметры отсутствуют, то браузер выставляет их в no . Поэтому убедитесь, что все нужные вам параметры выставлены в yes .
  • Когда не указан top/left , то браузер откроет окно с небольшим смещением относительно левого верхнего угла последнего открытого окна.
  • Если не указаны width/height , новое окно будет такого же размера, как последнее открытое.

Доступ к новому окну

Вызов window.open возвращает ссылку на новое окно. Она может быть использована для манипуляции свойствами окна, изменения URL, доступа к его переменным и т.п.

В примере ниже мы заполняем новое окно содержимым целиком из JavaScript:

Make a link open a new window (not tab) [duplicate]

Is there a way to make a link open a new browser window (not tab) without using javascript?

5 Answers 5

With pure HTML you can’t influence this — every modern browser (= the user) has complete control over this behavior because it has been misused a lot in the past.

HTML option

You can open a new window (HTML4) or a new browsing context (HTML5). Browsing context in modern browsers is mostly «new tab» instead of «new window». You have no influence on that, and you can’t «force» modern browsers to open a new window.

In order to do this, use the anchor element’s attribute target [1] . The value you are looking for is _blank [2] .

JavaScript option

Forcing a new window is possible via javascript — see Ievgen’s excellent answer below for a javascript solution.

(!) However, be aware, that opening windows via javascript (if not done in the onclick event from an anchor element) are subject to getting blocked by popup blockers!

[1] This attribute dates back to the times when browsers did not have tabs and using framesets was state of the art. In the meantime, the functionality of this attribute has slightly changed (see MDN Docu)

[2] There are some other values which do not make much sense anymore (because they were designed with framesets in mind) like _parent , _self or _top .

Форум

Справочник

window.open

Синтаксис

Аргументы

Описание, примеры

Метод open создает новое окно браузера , аналогично команде «Новое окно» в меню браузера. Обычно это не вкладка, а именно новое окно, но в некоторых браузерах можно настроить то или иное поведение явным образом.

Если параметр strUrl — пустая строка, то в окно будет загружен пустой ресурс about:blank.

В любом случае, загрузка осуществляется асинхронно. Создается пустое окно, загрузка ресурса в которое начнется уже после завершения исполнения текущего блока кода.

Связь между окнами

Метод open возвращает ссылку на новое окно, которая служит для обращения к нему и вызову его методов, если это соответствует ограничениям безопасности Same Origin.

Если окно с именем winName уже существует, то вместо открытия нового окна, strUrl загружается в существующее, ссылка на которое возвращается. При этом строка параметров не применяется.

В случае, когда окно открыть не удалось, например, оно заблокировано штатными Popup-blocker’ами Firefox/IE — вызов open вернет null.
Проверяйте его, если не хотите лишних ошибок в своих скриптах.

Указание пустого strUrl для существующего имени окна — удобный способ получить ссылку на это окно без его перезагрузки.

Если вы хотите открывать новое окно при каждом вызове open() — используйте для winName специальное значение ‘_blank’.

Строка параметров

Необязательная строка параметров состоит из списка разделенных запятой настроек нового окна. После открытия окна их уже нельзя будет изменить.

Если строки параметров нет или она пустая, то для нового окна будут взяты параметры по умолчанию.

Читайте также:  Обновление драйверов блютуз для windows 10 ноутбук

Если строка параметров указана, то не перечисленные в ней параметры будут отключены(кроме titlebar/close). Поэтому включите в ней свойства, которые нужны.

Если в параметрах не указаны размеры, то новое окно будет по размеру такое же, как последнее открытое.

Если не указана позиция нового окна, то оно откроется со сдвигом в 20-30 пикселей (зависит от браузера) от последнего открытого окна.
Такой сдвиг позволяет посетителю заметить, что открылось новое окно.
Если текущее окно максимизировано, то сдвига не будет: новое тоже будет максимизировано.

Основные кроссбраузерные параметры

Параметры, касающиеся элементов управления окна, могут быть жестко установлены в конфигурации браузера. В этом случае их указание в параметрах open() не даст нужного эффекта.

left/top Расстояние от левой/верхней границы окна операционной системы до границы нового окна. Новое окно не может быть создано за границами экрана height/width Высота/ширина в пикселях внутренности нового окна, включая полосы прокрутки, если они есть. Минимальное значение: 100 menubar Если этот параметр установлен в yes, то в новом окне будет меню. toolbar Если этот параметр установлен в yes, то в новом окне будет навигация (кнопки назад, вперед и т.п.) и панель вкладок location Если этот параметр установлен в yes, то в новом окне будет адресная строка directories Если этот параметр установлен в yes, то в новом окне будут закладки/избранное status Если этот параметр установлен в yes, то в новом окне будет строка состояния resizable Если этот параметр установлен в yes, то пользователь сможет изменить размеры нового окна. Рекомендуется всегда устанавливать этот параметр. scrollbars Если этот параметр установлен в yes, то новое окно при необходимости сможет показывать полосы прокрутки

Html javascript to open new window and close current window

I have a popup window and in that page I have the following code in the body.

The purpose is to have this popup window close when a user clicks on the image link, and to open a new page and be directed to http://www.example.com.

It works in IE and Chrome, but not in Firefox. The popup window closes but no new window is opened.

3 Answers 3

Yes, I can repro this — interesting. setTimeout works around it:

I can only guess that once the window closes (which happens before the hyperlink is followed) Firefox stops processing that page.

Edit: better make it 10ms delay — with 1ms Chrome doesn’t close the window.

– Eatdoku Sep 9 ’10 at 23:23

The question is actually solved for the opener but it didn’t help my issue (not wished: the new windows under firefox keep the same size as the current popup).

So I find following solution:

or this if the ppage should open in a new tab:

When you add some functionality to an element’s click event via javascript, that functionality is executed before the default click event (in this case, opening a new page), in order to allow for the possibility of intercepting and overriding the default event. The default behavior will only execute when and if the event returns a boolean value of true.

In this case, the additional functionality would be to close the window and my guess is that Firefox chooses to interpret this as «we’re all done here», so the click event never returns true, and thus the new page never gets opened.

Evgeny’s suggestion of using a short timeout would allow the click event to return true before the window is closed, thus allowing the new window to open.

Not the answer you’re looking for? Browse other questions tagged javascript window.open or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Оцените статью