Document

Open a URL in a new tab or window on button click in JavaScript

In JavaScript, you can use the window.open() method to open a URL in a new tab on a button click. It opens a new tab or a new browser window depending on the browser settings and the parameters passed.

  1. Select the button element using the querySelector() method.
  2. Add an event listener to the button.
  3. In the event handler, use the window.open() method to open the link in a new tab.

To open a new tab, pass _blank as a second parameter to window.open() or skip the second parameter entirely and only pass the URL. Suppose you have the following

button id="clickMe">Click Me!button> 

You want to ensure when the user clicks on the above button, a URL is opened in a new tab. Here is how you can do it in vanilla JavaScript:

const button = document.querySelector('#clickMe') // add click event listener button.addEventListener('click', () =>  // open a new tab const tab = window.open('https://attacomsian.com', '_blank') >) 

The above JavaScript code will open https://attacomsian.com in a new tab (or window), depending on the browser settings.

Another important thing you should know before using the window.open() method. The new tab or window is only opened as a direct result of a user action. In the above example, the URL is opened on the actual click event. However, if you make an asynchronous HTTP request when the user clicks and then opens a URL in a new tab on success, the browser will block the popup because it is not a direct user action. Here is an example that uses the Fetch API to make an AJAX call, and then open a new tab on a successful response:

button.addEventListener('click', () =>  // make an API call fetch('https://reqres.in/api/users') .then(res => res.json()) .then(json =>  // fail in Chrome - popup blocked const tab = window.open('https://attacomsian.com', '_blank') >) >) 

To make the above code work, we need to make a few changes. The first thing you should do is open an empty new window on click. Once the request is completed, update the actual window URL and set the focus. If the request fails, only close the window using the window.close() method. Here is the complete example that should work in all browsers:

button.addEventListener('click', () =>  // open an empty window const tab = window.open('about:blank') // make an API call fetch('https://reqres.in/api/users') .then(res => res.json()) .then(json =>  // TODO: do something with JSON response // update the actual URL tab.location = 'https://attacomsian.com' tab.focus() >) .catch(err =>  // close the empty window tab.close() >) >) 

To open a URL in a new window, make sure that the second parameter is the name of the window or empty. You can also specify the height and width of the window using the features attribute, as shown in the following example:

button.addEventListener('click', () =>  // open a new window const win = window.open('https://attacomsian.com', 'mysite', 'width=600,height=500') >) 

You might also like.

Источник

How to open a new tab in JavaScript? [SOLVED]

As a web developer, it is common to encounter situations where you want to open a new tab or window using JavaScript. This could be for various reasons such as opening a link to another website or displaying some content in a new tab. In this article, we will explore how to use window.open() method to open a new tab in JavaScript.

Using window.open() method to open a new tab

The window.open() method is a built-in JavaScript method that allows the opening of a new browser window or tab. This method takes two parameters, the URL of the page to be opened and the target attribute that specifies where to open the link. If the target attribute is not specified, the link will open in the current tab/window.

The syntax for using the window.open() method is as follows:

window.open(URL, name, specs, replace); 
  • URL : This parameter specifies the URL of the page to be opened. It is a mandatory parameter.
  • name : This parameter specifies the name of the window. It is an optional parameter.
  • specs : This parameter specifies the features of the opened window like width, height, and position. It is also an optional parameter.
  • replace : This parameter specifies whether to replace the current page in the history or not. It is also an optional parameter.

Let’s see an example of how to use the window.open() method to open a new tab. In this example, we will open the GoLinuxCloud homepage in a new tab.

        

Open a New Tab

Here we show you how to open a new tab using JavaScript

" target="newWindow">GoLinuxCloud
let windowObjectReference = null; function openRequestedTab(url, windowName) < if (windowObjectReference === null || windowObjectReference.closed) < windowObjectReference = window.open(url, windowName); >else < windowObjectReference.focus(); >> const link = document.querySelector("a[target='newWindow']"); link.addEventListener( "click", (event) => < openRequestedTab(link.href); event.preventDefault(); >, false ); 

In this example, we define a function openRequestedTab and an event listener that calls this function when a link is clicked, preventing the default behavior of opening the link in a new window.

The openRequestedTab function takes two arguments, url and windowName . It first checks if the global variable windowObjectReference is null or if the window it references has been closed. If either of these conditions is true, it opens a new window using the window.open method with the given url and windowName arguments, and assigns the reference to the windowObjectReference variable.

If the windowObjectReference variable is not null and the window it references is still open, the function focuses on the existing window using the window.focus() method. The event listener is added to a link element in the HTML document that has a target attribute set to «newWindow» . When the link is clicked, the event listener calls the openRequestedTab function with the link’s href attribute as the url argument, which opens the linked URL in a new tab or window depending on the user’s browser settings. The event.preventDefault() method is called to prevent the default behavior of the link element, which is to navigate to the GoLinuxCloud URL in the current tab.

Summary

In this article, we have discussed how to open a new tab in JavaScript using the window.open() method. We have seen the syntax of this method and explored an example that demonstrate how to use it. By using this method, web developers can easily open new tabs or windows in their web applications.

References

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment Cancel reply

JavaScript Tutorial

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