Javascript open url in current window

Window open()

The open() method opens a new browser window, or a new tab, depending on your browser settings and the parameter values.

See Also:

Syntax

Parameters

Deprecated

  • true — URL replaces the current document in the history list
  • false — URL creates a new entry in the history list

Warning

Chrome throws an exception when using this parameter.

Return Value

More Examples

Open an about:blank page in a new window/tab:

Open a new window called «MsgWindow», and write some text into it:

var myWindow = window.open(«», «MsgWindow», «width=200,height=100»);
myWindow.document.write(«

This is ‘MsgWindow’. I am 200px wide and 100px tall!

«);

Replace the current window with a new window:

var myWindow = window.open(«», «_self»);
myWindow.document.write(«

I replaced the current window.

«);

Open a new window and control its appearance:

window.open(«https://www.w3schools.com», «_blank», «toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400»);

Open a new window. Use close() to close the new window:

function openWin() <
myWindow = window.open(«», «myWindow», «width=200,height=100»); // Opens a new window
>

function closeWin() myWindow.close(); // Closes the new window
>

Open a new window. Use the name property to return the name of the new window:

var myWindow = window.open(«», «MsgWindow», «width=200,height=100»);
myWindow.document.write(«

This window’s name is: » + myWindow.name + «

«);

Using the opener property to return a reference to the window that created the new window:

var myWindow = window.open(«», «myWindow», «width=200,height=100»); // Opens a new window
myWindow.document.write(«

This is ‘myWindow’

«); // Text in the new window
myWindow.opener.document.write(«

This is the source window!

«); // Text in the window that created the new window

Browser Support

open() is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Источник

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 .

Читайте также:  Php вывод элементов массива массиву

Значения:

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

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. инлайновые значения вызывают неожиданное поведение ссылки при взаимодействии с ней (и не только). Важно и то, что они также передают неправильную семантику скринридерам.

Источник

How to Open URL Using JavaScript in Same or New Tab/Window

Normally we navigate from one page to another by clicking an HTML link but you can open an URL using JavaScript. It will open the link in the new browser window or tab based on your browser settings.

The window.open() method is used to open an URL using JavaScript. This method takes some parameters to customize how and where the link should open in the browser. It can open the link in a new tab or in the current tab depending on the parameter value.

It might sound complex to you, but the interesting thing is that you can do everything just by writing a single line of JavaScript code.

In this article, I will show you how to use the window.open() method to open an URL in the browser automatically using JavaScript. You will also see all the customization options that you can use with this method.

Open URL Using JavaScript window.open() Method

You can call the open() method on the browser window object. You don’t need to pass any parameter to this method because it doesn’t have any required parameters.

If you call the window.open() method as it is, the browser will open a new empty tab. But you can pass an URL string in the first parameter.

By default, when you call this method with an URL, it will open that URL in a new tab. You can change this behavior by using other parameters.

This method can accept up to 3 optional parameters. These are url , target , and features . This is the syntax you have to use to call the window.open() method.

// Without any parameter window.open(); // With an URL window.open(url); // With an URL and target window.open(url, target); // With an URL, target and features window.open(url, target, features); 

These are the 4 ways you can call this method in your JavaScript code. You need to use different values in those parameters to modify how it works.

Let’s see how and what types of values you can provide to this method while calling it.

How to Open URL Using JavaScript in Same or New Tab/Window

Parameters of The window.open() Method

This is the list of all optional parameters and their values:

It is a string that specifies the URL or a path that you want to open. You can give a full URL or a relative path. If you pass an empty string («») in this place, browsers will ignore it and open a blank page.

// Full URL window.open("https://www.example.com"); // Relative URL window.open("/posts"); 

It determines where to display the URL. You can use all the target attributes of the HTML tag. You need to pass its value as a string.

  • _self – It opens the URL in the current tab by replacing the opened page.
  • _blank – It opens the URL in a new tab. This is the default value.
  • _parent – It loads the URL into the parent frame. If there is no parent, behave as _self.
  • _top – It opens the URL by replacing any framesets. If no frameset, behave as _top.

You can pass any custom text other than these values if you want. It will work as the name of the window. You are able to extract your custom text from the object that window.open() method returns.

We will look into the returned value and how you can get the text from it in the later section.

It is a comma-separated list of items without whitespaces that can customize the new window. But this parameter is rarely used. Because browsers apply these parameter values differently.

Some browsers also don’t use all the values that this parameter supports. This is the list of items that you can choose for this parameter:

Open URL in The New Tab With JavaScript

You have learned about the window.open() method and its parameters. Now let’s see how you can use this method to open a URL in the new tab.

window.open("https://www.webmound.com/blog", "_blank", "location=yes,height=570,width=520,status=yes"); 

In this example, I am using all 3 parameters in the window.open() method. I am setting an URL that I want to open. In the second parameter, I have used «_blank» because I want to open this link in the new window.

This value is responsible to open a new tab in the browser. I am also providing some features for the new window in the third parameter.

Note: If you don’t pass any target or an empty string («»), the browser will use «_blank» by default and open the link in a new window.

Open URL in The Same Tab Using JavaScript

It is very easy to open an URL in the same tab using window.open() method in Javascript. You just have to set the target parameter to «_self».

window.open("https://www.webmound.com/blog", "_self"); 

When the browser executes this method, it will open this URL in the current tab by replacing the current page.

Return Value From the window.open() Method

When the browser executes the window.open() method, it will return the window object. But if the browser fails for any reason, it will return null .

This method also returns a null value if the features parameter has noopener=yes in it.

const handle = window.open("https://www.webmound.com/blog", "_blank", "noopener=yes"); console.log(handle); // null const handle2 = window.open("https://www.webmound.com/blog", "_blank"); console.log(handle2); // window object 

In this example, I am calling the window.open() method twice. I used noopener=yes in the first call. Therefore, it is returning a null value.

But in the second call, I am not using that feature parameter. So, I am getting a window object as the return value.

As you know, you can pass a custom string in the target parameter. You can also get that custom string back from the window object, returned from the window.open() method.

const handle = window.open("https://www.webmound.com/blog", "Web_Mound"); console.log(handle.name); // Web_Mound 

I am calling the window.open() method with the «Web_Mound» value in its second parameter. When this method returns a new window object, I can access the name property on that object to get the value back.

Conclusion

It is very easy to open an URL using JavaScript. You just have to write a single line of code to do it. You will call the window.open() method with the URL that you want to open.

This method also has some customization options. By passing different parameter values, it is possible to modify the default behavior.

You can open your link in the same tab or in a new tab. You can also control how the new window will look by using the features parameter.

I hope it was helpful. You have learned how to open an URL in JavaScript using window.open() method.

Источник

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