Как открыть ссылку через javascript
Перейти к содержимому

Как открыть ссылку через javascript

  • автор:

Window: open() method

The open() method of the Window interface loads a specified resource into a new or existing browsing context (that is, a tab, a window, or an iframe) under a specified name.

Syntax

Parameters

A string indicating the URL or path of the resource to be loaded. If an empty string ( «» ) is specified or this parameter is omitted, a blank page is opened into the targeted browsing context.

A string, without whitespace, specifying the name of the browsing context the resource is being loaded into. If the name doesn’t identify an existing context, a new context is created and given the specified name. The special target keywords, _self , _blank , _parent , and _top , can also be used.

This name can be used as the target attribute of <a> or <form> elements.

A string containing a comma-separated list of window features in the form name=value — or for boolean features, just name . These features include options such as the window’s default size and position, whether or not to open a minimal popup window, and so forth. The following options are supported:

If this feature is enabled, it requests that a minimal popup window be used. The UI features included in the popup window will be automatically decided by the browser, generally including an address bar only.

If popup is not enabled, and there are no window features declared, the new browsing context will be a tab.

Note: Specifying any features in the windowFeatures parameter, other than noopener or noreferrer , also has the effect of requesting a popup.

To enable the feature, specify popup either with no value at all, or else set it to yes , 1 , or true .

Example: popup=yes , popup=1 , popup=true , and popup all have identical results.

width or innerWidth

Specifies the width of the content area, including scrollbars. The minimum required value is 100.

height or innerHeight

Specifies the height of the content area, including scrollbars. The minimum required value is 100.

left or screenX

Specifies the distance in pixels from the left side of the work area as defined by the user’s operating system where the new window will be generated.

Specifies the distance in pixels from the top side of the work area as defined by the user’s operating system where the new window will be generated.

If this feature is set, the new window will not have access to the originating window via Window.opener and returns null .

When noopener is used, non-empty target names, other than _top , _self , and _parent , are treated like _blank in terms of deciding whether to open a new browsing context.

If this feature is set, the browser will omit the Referer header, as well as set noopener to true. See rel=»noreferrer» for more information.

Note: Requested position ( top , left ), and requested dimension ( width , height ) values in windowFeatures will be corrected if any of such requested value does not allow the entire browser popup to be rendered within the work area for applications of the user’s operating system. In other words, no part of the new popup can be initially positioned offscreen.

Return value

A WindowProxy object. The returned reference can be used to access properties and methods of the new window as long as it complies with the same-origin policy security requirements.

Description

The Window interface’s open() method takes a URL as a parameter, and loads the resource it identifies into a new or existing tab or window. The target parameter determines which window or tab to load the resource into, and the windowFeatures parameter can be used to control to open a new popup with minimal UI features and control its size and position.

Note that remote URLs won’t load immediately. When window.open() returns, the window always contains about:blank . The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.

Examples

Opening a new tab

Opening a popup

Alternatively, the following example demonstrates how to open a popup, using the popup feature.

Warning: Modern browsers have built-in popup blockers, limiting the opening of such popups to being in direct response to user input. Popups opened outside the context of a click may cause a notification to appear, giving the option to enable or discard them.

It is possible to control the size and position of the new popup:

Progressive enhancement

In some cases, JavaScript is disabled or unavailable and window.open() will not work. Instead of solely relying on the presence of this feature, we can provide an alternative solution so that the site or application still functions.

Provide alternative ways when JavaScript is disabled

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. The goal and the idea are to provide (and not impose) to the user a way to open the referenced resource.

JavaScript

The above code solves a few usability problems related to links opening popups. The purpose of the event.preventDefault() in the code is to cancel the default action of the link: if the event listener for click 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 event listener for click is ignored, and the browser loads the referenced resource in the target frame or window that has the name «WikipediaWindowName» . If no frame nor window has the name «WikipediaWindowName» , then the browser will create a new window and name it «WikipediaWindowName» .

Note: For more details about the target attribute, see <a> or <form> .

Reuse existing windows and avoid target=»_blank»

Using «_blank» as the target attribute value will create several new and unnamed windows on the user’s desktop that cannot be recycled or reused. Try to provide a meaningful name to your target attribute and reuse such target attribute on 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.

Here is an example where a secondary window can be opened and reused for other links:

JavaScript

Same-origin policy

If the newly opened browsing context does not share the same origin, the opening script will not be able to interact (reading or writing) with the browsing context’s content.

For more information, refer to the Same-origin policy article.

Accessibility

Avoid resorting to window.open()

It is preferable to avoid resorting to window.open() , for several reasons:

  • Modern browsers offer a popup-blocking feature.
  • Modern browsers offer tab-browsing, and tab-capable browser users prefer opening new tabs to opening new windows in most situations.
  • Users may use browser built-in features or extensions to choose whether to open a link in a new window, in the same window, in a new tab, the same tab, or in the background. Forcing the opening to happen in a specific way, using window.open() , will confuse them and disregard their habits.
  • Popups don’t have a menu toolbar, whereas new tabs use the user interface of the browser window; therefore, many users prefer tab-browsing because the interface remains stable.

Never use window.open() inline in HTML

Avoid <a href=»#» onclick=»window.open(…);»> or <a href=»javascript:window\.open(…)» …> .

These bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers.

If necessary, use a <button> element instead. In general, you should only use a link for navigation to a real URL.

Always identify links leading to a secondary window

Identify links that will open new windows in a way that helps navigation for users.

The purpose is to warn users 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 (in the case of a popup, no toolbar provides a «Previous» button to get back to the previous window).

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).

Как открыть ссылку через javascript

In HTML, the anchor tag is used to open new windows and tabs in a very straightforward manner. However, there is a need to do the same using JavaScript. In JavaScript, window.open() proves to be helpful. The window.open() method is used to open a new browser window or a new tab depending on the browser setting and the parameter values.

Syntax:

Note: All the parameters are optional.

Approach:

  • To open a URL in a new window, make sure that the second parameter is not _blank.
  • The other parameters can be varied accordingly as per the need of the new window.

Example 1:

Output:

  • Before Clicking on the Button:

  • After Clicking on the Button:

Example 2: Use Anchor tag to open URL in a new window.

Output:

  • Before Clicking on GeeksforGeeks:

  • After Clicking on GeeksforGeeks:

Example 3: Use the Input tag to open the URL in a new window.

Output:

  • Before Clicking on the Button:

  • After Clicking on the Button:

Supported Browsers: The browsers are supported by the window.open() method are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari

HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.

Откройте URL-адрес в новой вкладке в JavaScript/jQuery.

В этом посте будет обсуждаться, как открыть ссылочный ресурс ссылки на новой вкладке в JavaScript и jQuery.

1. Использование окна open() метод

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

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

Как открыть ссылку в новом окне с помощью JavaScript

JavaScript предлагает полезный способ открыть ссылку в новом окне, потому что вы контролируете, как окно будет выглядеть и где оно будет размещено на экране, путем включения спецификаций.

Деги Адиль / EyeEm / Getty Images

Синтаксис для метода JavaScript Window Open ()

Чтобы открыть URL-адрес в новом окне браузера, используйте метод Javascript open (), как показано здесь:

window.open (URL, имя, спецификации, заменить)

Параметр URL

Помимо открытия окна, вы также можете настроить каждый из параметров. Например, приведенный ниже код открывает новое окно и определяет его внешний вид с помощью параметров.

Введите URL-адрес страницы, которую хотите открыть, в новом окне. Если вы не укажете URL-адрес, откроется новое пустое окно:

window.open ("https://www.somewebsite.com", "_blank", "toolbar = yes, top = 500, left = 500, width = 400, height = 400");

Имя Параметр

Параметр name устанавливает цель для URL-адреса. URL-адрес открывается в новом окне по умолчанию и обозначается следующим образом:

  • _blank: Открывает новое окно для URL.

Другие варианты, которые вы можете использовать, включают:

  • _self: Заменяет текущую страницу URL-адресом.
  • _parent: Загружает URL-адрес в родительский фрейм.
  • _Топ: Заменяет все загруженные наборы фреймов.

Технические характеристики Параметр

Параметр specs — это то место, где вы настраиваете новое окно, вводя список, разделенный запятыми, без пробелов. Выберите одно из следующих значений.

  • высота = пикселей: Эта спецификация устанавливает высоту нового окна в пикселях. Минимальное значение, которое можно ввести, — 100.
  • ширина = пикселей: Эта спецификация устанавливает ширину нового окна в пикселях. Минимальное значение — 100.
  • left = пикселей: Эта спецификация устанавливает левую позицию нового окна. Нельзя вводить отрицательные значения.
  • top = пикселей: Эта спецификация устанавливает верхнюю позицию нового окна. Отрицательные значения использовать нельзя.
  • menubar = да | нет | 1 | 0: Используйте эту спецификацию, чтобы указать, отображать ли строку меню. Используйте слова «да / нет» или двоичное значение 1/0.
  • статус = да | нет | 1 | 0: Указывает, нужно ли добавлять строку состояния. Как и в строке меню, вы можете использовать слова или двоичные значения.

Некоторые спецификации зависят от браузера:

  • расположение = да | нет | 1 | 0: Эта спецификация указывает, следует ли отображать поле адреса. Только для браузера Opera.
  • resizeable = да | нет | 1 | 0: Определяет, можно ли изменить размер окна. Только для использования с IE.
  • расположение = да | нет | 1 | 0: Указывает, следует ли отображать полосы прокрутки. Совместим только с IE, Firefox и Opera.
  • панель инструментов = да | нет | 1 | 0: Определяет, показывать ли панель инструментов браузера. Совместим только с IE и Firefox.

Заменить параметр

Этот необязательный параметр имеет только одну цель — указать, заменяет ли URL, открывающийся в новом окне, текущую запись в списке истории браузера или отображается как новая запись.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *