Html open link in this window

window.open()

Открывает ссылку в новом окне, в новой вкладке или в iframe.

Время чтения: меньше 5 мин

Это незавершённая статья. Вы можете помочь её закончить! Почитайте о том, как контрибьютить в Доку.

Кратко

Скопировать ссылку «Кратко» Скопировано

Метод open ( ) объекта window позволяет открывать ссылки в новом окне, в новой вкладке или в iframe.

Простой пример

Скопировать ссылку «Простой пример» Скопировано

 window.open('https://practicum.yandex.ru/'); window.open('https://practicum.yandex.ru/');      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Метод open ( ) имеет три опциональных параметра:

 window.open(url, target, windowFeatures); window.open(url, target, windowFeatures);      

url – строка, которая содержит относительный или абсолютный URL.

target – строка, которая указывает где откроется новое окно. Он может принимать те же значения, что и атрибут target тега : имя окна или одно из ключевых слов _self , _blank , _parent , _top .

window Features – строка, которая позволяет детально описать, как будет выглядеть новое окно. Опции в строке указываются через запятую в формате name = value , для булевых типов значение можно опустить.

Вызвать метод без параметров тоже можно, по умолчанию будет открыта чистая вкладка about : blank .

Значения:

Скопировать ссылку «Значения:» Скопировано

width or inner Width / height or inner Height — определит ширину и высоту содержимого окна включая полосы прокрутки. Минимальное возможное значения — 100px.

left or screen X / top or screen Y — здесь можно указать расстояние от левой верхней части (или рабочей области) экрана пользователя, на котором откроется окно.

popup — открывает ссылку в новом окне

menubar — отвечает за отображение строки меню

toolbar — управляет показом кнопок панели инструментов и панели закладок

location — отвечает за показ адресной строки

resizable — позволяет включить/выключить возможность пользователям изменять размеры окна

scrollbars — отображение полос прокрутки

status — отображение строки состояния

noopener — помогает повысить безопасность сайта, так как предотвращает доступ открываемого ресурса к текущей странице (через сеанс браузера).
При использовании noopener значения второго параметра метода open ( ) (кроме _top , _self , _parent ), будут обработаны как _blank

noreferrer — предотвращает передачу информации об исходном ресурсе на целевой. При установке этого значения как true noopener также становится true .

Примеры использования

Скопировать ссылку «Примеры использования» Скопировано

 window.open("https://ya.ru/", "_self"); // ссылка откроется в текущем окне window.open("https://ya.ru/", "yandex", "popup"); // ссылка откроется в новом окне, которое примет имя "yandex" window.open("https://ya.ru/", "_blank", "top=100, left=100, width=400, height=500"); // ссылка откроется в новом окне, величина отступов и размеры окна будут соответствовать указанным window.open("https://ya.ru/", "_self"); // ссылка откроется в текущем окне window.open("https://ya.ru/", "yandex", "popup"); // ссылка откроется в новом окне, которое примет имя "yandex" window.open("https://ya.ru/", "_blank", "top=100, left=100, width=400, height=500"); // ссылка откроется в новом окне, величина отступов и размеры окна будут соответствовать указанным      

Возможности

Скопировать ссылку «Возможности» Скопировано

Использование метода open ( ) позволяет получить ссылку на новое окно и взаимодействовать с ним, например:

 const newWindow = window.open("", "new window", "popup");newWindow.document.write("

Hello, World!

");
// откроется новое окно с текстом "Hello, World!"
const newWindow = window.open("", "new window", "popup"); newWindow.document.write("

Hello, World!

"
); // откроется новое окно с текстом "Hello, World!"

Особенности применения

Скопировать ссылку «Особенности применения» Скопировано

Авторы MDN рекомендуют использовать метод open ( ) в крайних случаях и (никогда!) не прибегать к встроенному (inline) использованию window . open ( ) .

  a href='#' onclick='window.open(`any url`)'>     

У метода open ( ) есть несколько недостатков:

  1. многие браузеры блокируют попапы.
  2. open ( ) решает за пользователя, как именно открыть ссылку. Улучшится ли пользовательский опыт, если чтению контента будут мешать неожиданно всплывающие окна или переходы на новую вкладку (вместо открытия их в фоновом режиме)? Вряд ли.
  3. инлайновые значения вызывают неожиданное поведение ссылки при взаимодействии с ней (и не только). Важно и то, что они также передают неправильную семантику скринридерам.

Источник

Hyperlinks are used to jump from one page to another. A hyperlink commonly opens in the same page by default. But it is possible to open hyperlinks in a separate window.

Opening external links in a new tab or window will make people leave your website. In this way, you prevent your visitors from returning to your website. Remember that visitors can open a new tab themselves and are irritated when a link opens in a new tab or window without their consent. That’s why it’s recommended to avoid opening links in a new tab or window. However, there can be specific situations when this is needed, and in this snippet, we’ll demonstrate how it can be done.

When it is needed to tell the browser where to open the document, the target attribute is used.

How to Add target=»_blank» Attribute to Anchor Link

The target attribute determines where the linked document will open when the link is clicked. It opens the current window by default. To open a link in a new window, you need to add the target=»_blank» attribute to your anchor link, like the following.

html> html> head> title>Title of the document title> head> body> h1>Hyperlink Example h1> p> This a href="https://www.w3docs.com/" target="_blank">hyperlink a> will open in a new tab. p> body> html>

Result

In the given example, when the visitor clicks on the hyperlink, it opens in a new window or tab.

There is another way of opening a hyperlink in a new tab by using the JavaScript window.open function with the onclick event attribute like this:

html> html> head> title>Title of the document title> style> .link:hover < text-decoration: underline; color: blue; cursor: pointer; > style> head> body> h1>Hyperlink Example with JavaScript h1> p>Visit our website p> a href="https://w3docs.com" onclick="window.open(this.href, '_blank', 'width=500,height=500'); return false;" class="link">W3docs a> body> html>

Let’s see one more example, where besides the target attribute, we also add a rel attribute with the “noopener noreferrer” value. The rel attribute is not mandatory, but it’s recommended as a security measure.

html> html> head> title>Title of the document title> head> body> a target="_blank" rel="noopener noreferrer" href="https://www.lipsum.com/">Lorem Ipsum a> p>This link will open in a new browser tab or a new window. p> body> html>

Источник

Links are found in nearly all web pages. Links allow users to click their way from page to page.

HTML links are hyperlinks.

You can click on a link and jump to another document.

When you move the mouse over a link, the mouse arrow will turn into a little hand.

Note: A link does not have to be text. A link can be an image or any other HTML element!

The link text is the part that will be visible to the reader.

Clicking on the link text, will send the reader to the specified URL address.

Example

This example shows how to create a link to W3Schools.com:

By default, links will appear as follows in all browsers:

  • An unvisited link is underlined and blue
  • A visited link is underlined and purple
  • An active link is underlined and red

Tip: Links can of course be styled with CSS, to get another look!

By default, the linked page will be displayed in the current browser window. To change this, you must specify another target for the link.

The target attribute specifies where to open the linked document.

The target attribute can have one of the following values:

  • _self — Default. Opens the document in the same window/tab as it was clicked
  • _blank — Opens the document in a new window or tab
  • _parent — Opens the document in the parent frame
  • _top — Opens the document in the full body of the window

Example

Use target=»_blank» to open the linked document in a new browser window or tab:

Absolute URLs vs. Relative URLs

Both examples above are using an absolute URL (a full web address) in the href attribute.

A local link (a link to a page within the same website) is specified with a relative URL (without the «https://www» part):

Example

Absolute URLs

W3C

Google

Relative URLs

HTML Images

CSS Tutorial

To use an image as a link, just put the tag inside the tag:

Example

Use mailto: inside the href attribute to create a link that opens the user’s email program (to let them send a new email):

Example

To use an HTML button as a link, you have to add some JavaScript code.

JavaScript allows you to specify what happens at certain events, such as a click of a button:

Example

Tip: Learn more about JavaScript in our JavaScript Tutorial.

The title attribute specifies extra information about an element. The information is most often shown as a tooltip text when the mouse moves over the element.

Источник

Kris Koishigawa

Kris Koishigawa

How to Use HTML to Open a Link in a New Tab

Tabs are great, aren’t they? They allow the multitasker in all of us to juggle a bunch of online tasks at the same time.

Tabs are so common now that, when you click on a link, it’s likely it’ll open in a new tab.

If you’ve ever wondered how to do that with your own links, you’ve come to the right place.

The Anchor Element

If you click on the link above, the browser will open the link in the current window or tab. This is the default behavior in every browser.

To open a link in a new tab, we’ll need to look at some of the other attributes of the anchor element’s other attributes.

The Target Attribute

This attribute tells the browser how to open the link.

To open a link in a new tab, just set the target attribute to _blank :

Now when someone clicks on the link, it will open up in a new tab, or possibly a new window depending on the person’s browser settings.

Security concerns with target=»_blank»

I strongly recommend that you always add rel=»noreferrer noopener» to the anchor element whenever you use the target attribute:

This results in the following output:

The rel attribute sets the relationship between your page and the linked URL. Setting it to noopener noreferrer is to prevent a type of phishing known as tabnabbing.

What is tabnabbing?

Tabnabbing, sometimes called reverse tabnabbing, is an exploit that uses the browser’s default behavior with target=»_blank» to gain partial access to your page through the window.object API.

With tabnabbing, a page that you link to could cause your page to redirect to a fake login page. This would be hard for most users to notice because the focus would be on the tab that just opened – not the original tab with your page.

Then when a person switches back to the tab with your page, they would see the fake login page instead and might enter their login details.

If you’re interested in learning more about how tabnabbing works and what bad actors can do with the exploit, check out Alex Yumashev’s article and this one by OWASP.

If you’d like to see a safe working example, check out this page and its GitHub repo for more information about the exploit and the rel attribute.

In summary

It’s easy to use HTML to open a link in a new tab. You just need an anchor ( ) element with three important attributes:

  1. The href attribute set to the URL of the page you want to link to,
  2. The target attribute set to _blank , which tells the browser to open the link in a new tab/window, depending on the browser’s settings, and
  3. The rel attribute set to noreferrer noopener to prevent possible malicious attacks from the pages you link to.

Again, here’s a full working example:

Which results in the following output in the browser:

Thanks again for reading. Happy coding.

Источник

Читайте также:  Linking Pages in HTML
Оцените статью