Href opens in new windows

Open link in new tab or window [duplicate]

Is it possible to open an a href link in a new tab instead of the same tab?

4 Answers 4

You should add the target=»_blank» and rel=»noopener noreferrer» in the anchor tag.

Adding rel=»noopener noreferrer» is not mandatory, but it’s a recommended security measure. More information can be found in the links below.

It shouldn’t be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user’s browser. Some people like tabs; some like new windows.

Using _blank will tell the browser to use a new tab/window, depending on the user’s browser configuration and how they click on the link (e.g. middle click, Ctrl +click, or normal click).

set the target attribute of your element to «_tab»

EDIT: It works, however W3Schools says there is no such target attribute: http://www.w3schools.com/tags/att_a_target.asp

EDIT2: From what I’ve figured out from the comments. setting target to _blank will take you to a new tab or window (depending on your browser settings). Typing anything except one of the ones below will create a new tab group (I’m not sure how these work):

How to Make Links Open in a New Window or Tab

How to Make Links Open in a New Window or Tab

I was asked by a visitor how he could make hyperlinks on his website open a new browser window or tab when clicked. This article answers that question.

Prerequisites

Since the visitor did not specify which web editor he was using, I will assume here that he is working directly in HTML.

Note that this does not mean you cannot follow this tutorial if you use a visual web editor, or if your website uses some sort of blogging software. It merely means that you will need to somehow access the HTML code of your page so that you can modify it. Most web editors and blogging software allow you to do this.

For example, if you are using Expression Web, you can modify the HTML code of your web page by switching to the Code mode. Instructions for this can be found in the article How to Insert HTML Code into a Web Page with Expression Web. Similarly, Dreamweaver users can follow the steps given in How to Insert Raw HTML Code in Dreamweaver, BlueGriffon users the tutorial How to Insert HTML Code in BlueGriffon, and KompoZer users the guide How to Insert HTML in KompoZer.

The short answer is: just add a target=»_blank» attribute to your links (anchor tags).

For example, if you have a link that says the following:

Change the above so that it now says:

Now when your visitors click that link, it will open in a new window or tab (depending on which web browser they are using and how they configured that browser).

Note that if your web page uses the «strict» DOCTYPE of XHTML 1.0 or 1.1, you will not be able to do the above and still have your page validate as correct. However, I suspect virtually nobody uses those, so don’t worry if you don’t understand what I just said in this paragraph. The «transitional» versions of those DOCTYPEs are fine, though, since the target attribute is still supported there.

Читайте также:  Драйвера для windows 10 мышь genius

If you are using Expression Web, Dreamweaver, BlueGriffon or KompoZer, just click somewhere in the link that you want to modify, switch to the mode that allows you to change the HTML code (see the tutorials listed earlier in the Prerequisites section to find out how to do this), and add the target=»_blank» attribute.

It Doesn’t Have the Benefit You Think It Confers

I know that some new webmasters seem to have got the impression that causing external links to open in a new window helps to keep people from leaving your website. This is an erroneous assumption. If someone clicks on a link and wants to return to your site, they will simply hit the Back button on their browser. Most people, even non-computer-geeks, learn this feature of their browser within a short time of discovering the Internet. The power users learn, in addition, how to right click a link and select «Open in a new tab» (or window) when they need a link to be displayed in a separate tab or window.

When you create links that open in a new window, you are actually preventing newcomers from returning to your website. You may think that they will know how to simply switch back to the original window. My experience with such people suggests otherwise; they are stymied by the Back button not working, and are not even aware that they are looking at a new tab or window. When they can’t figure out how to solve the problem, they will give up and move on to other things.

The situation is not better with experienced users. While they can figure out that they are looking at a new tab or window, and can switch back, they tend to get very irritated at your site for opening windows without their permission. After all, they are power users: if they wanted to open a new window, they will open it themselves; they don’t want you to do it without their consent. It’s worse if all your links open in new windows (leading to the comedic situation described in my article about usability mistakes made by amateur webmasters).

It Makes Your Site Vulnerable to Phishing Attacks

At the time this is written, when you open a new page with target=»_blank» , the site you link to gains access to the window/tab containing your page and is able to change it (in the visitor’s browser) to display a different web address.

This not only thwarts your attempt to keep visitors at your site (if that’s your purpose), it’s also a potential danger to them. For example, if you have a login page, the linked-to site may replace it with one on another site that looks like yours, but actually collects your visitor’s login details. This kind of attack is called «phishing». Even if your site does not have facilities for visitors to log in, the linked-to site can replace it with a page that delivers malware.

This vulnerability is not hypothetical. The people from the Google Security Team have noted a «significant number of reports» of such «tabnabbing» being used to deliver malware.

Technical details (only for those who are interested): the newly open site gains limited access to your page via the JavaScript window.opener object. This is a read/write object that they can manipulate. It has a property called window.opener.location that can be changed, causing the browser to go to a new URL instead of staying at your page. If you don’t understand this paragraph, skip it. It’s merely the technical version of the explanation given earlier.

You can prevent it from happening in some browsers by adding rel=»noopener noreferrer» to your link. With this added, the above example becomes:

Theoretically, either rel=»noopener» or rel=»noreferrer» is sufficient to prevent this problem, with rel=»noopener» being the correct attribute to use. (The other one, rel=»noreferrer» , has a side-effect in that the browser will also withhold the referring URL.) However, at this time, not all browsers support rel=»noopener» . Likewise, rel=»noreferrer» is also not supported by some browsers. Since the list of browsers that support either attribute is not identical, if you want this protection from the greatest subset of browsers possible, you will probably need to use both.

Читайте также:  Prolific pl2303 driver mac os

That said, the workaround only helps with the later versions of Chrome, Firefox and Safari. Internet Explorer does not have such a facility, although from my cursory test, version 11 seems to be immune to the attack in its default security zone. I’m not sure about Microsoft Edge.

In other words, the method detailed above is not 100% foolproof. The best way to avoid the problem is to use normal links, without target=»_blank» .

Conclusion

My general recommendation is to avoid opening links in a new window or tab, if possible. Of course there may be specific instances where this is needed (which is why such a facility exists in the first place, for those rare cases where it may be required). If so, you may want to warn your visitors by saying something like «opens in a new window» next to your link (if it’s appropriate). It won’t help the average Internet user, who won’t know what you are talking about or how to deal with it, and it won’t guard them from attacks using your site, but at least you will won’t irritate the more experienced Internet visitors.

Copyright © 2015-2019 Christopher Heng. All rights reserved.
Get more free tips and articles like this, on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/.

thesitewizard™ News Feed (RSS Site Feed)

Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.

Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.

HTML Open Link in New Window

You can use the HTML code on this page to force a link to open in a new window.

Example

As the above example demonstrates, to open a link in a new window, you simply add target=»_blank» to the anchor tag. Everything else stays as a normal link.

If you have many links, and you add target=»_blank» to each one, they will all open in their own blank window. This could become quite annoying for the user—especially if you have many links that each open in their own tab or window. Users could avoid clicking on links if a blank window opens every time they click.

There is a way to overcome this issue. Read on…

Reloading the Blank Window/Tab

Instead of calling your window _blank , you can give it a name of your choosing. Then all URLs will load in that same tab (as long as you use the same name).

For example, if you have a policy of loading all external links in a separate tab, you could call that tab, say, external . Then each link that contains target=»external» will open in that window/tab. Doing this ensures that new windows aren’t going to be popping up every time a user clicks on a link.

Here’s an example of what happens when you use target=»_blank» for all links:

And here are the same links but with target=»external» (but this could be any name you choose):

There are other keywords that can be used with target as well as various implications depending on the names of windows/tabs that are already open, whether they’re sandboxed, etc. See the W3C website if you’re interested.

Creating a «Popup Window»

You can also use JavaScript to open a new window. Using JavaScript, you can also specify what the window should look like. This is a common technique for creating a «popup window». For more info, see Popup Windows.

You can do much more with HTML links. Here are more HTML link codes — each one catering for a specific purpose.

javascript window.location in new tab

I am diverting user to some url through window.location but this url opens in the same tab in browser. I want it to be open in new tab. Can I do so with window.location? Is there another way to do this action?

Читайте также:  Агент политики ipsec отключить windows 10

7 Answers 7

I don’t think there’s a way to do this, unless you’re writing a browser extension. You could try using window.open and hoping that the user has their browser set to open new windows in new tabs.

The second parameter is what makes it open in a new window. Don’t forget to read Jakob Nielsen’s informative article 🙂

You can even use

This will open it on the same tab if the pop-up is blocked.

This works for me on Chrome 53. Haven’t tested anywhere else:

with jQuery its even easier and works on Chrome as well

Rather going for pop up,I personally liked this solution, mentioned on this Question thread JavaScript: location.href to open in new window/tab?

We have to dynamically set the attribute target=»_blank» and it will open it in new tab. document.getElementsByTagName(«a»)[0].setAttribute(‘target’, ‘_blank’)

If you want to open in new window, get the href link and use window.open

var link = document.getElementsByTagName(«a»)[0].getAttribute(«href»);

Don’t provide the second parameter as _blank in the above.

Форум

Справочник

window.open

Синтаксис

Аргументы

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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