- Open a URL in a new tab or window on button click in JavaScript
- You might also like.
- How to open a new tab in JavaScript? [SOLVED]
- Using window.open() method to open a new tab
- Summary
- References
- Leave a Comment Cancel reply
- JavaScript Tutorial
- Window open()
- See Also:
- Syntax
- Parameters
- Deprecated
- Warning
- Return Value
- More Examples
- Browser Support
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.
- Select the button element using the querySelector() method.
- Add an event listener to the button.
- 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.
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
- Beginner Guide
- Define Global Variable
- Working with Object Literals
- Working with Template Literals
- Classes Overview
- Subclass Examples
- Iterators and Generators
- Error Handling
- Date Formatting
- parseFloat()
- Array.pop()
- Array.slice()
- Array.unshift()
- Array.join()
- Array.findIndex()
- Array Slicing Methods
- Remove Element from Array
- Check Array is Empty
- Create Unique Array of Objects
- Convert Array to String
- String.toLowerCase()
- String.toString()
- String.trimEnd()
- String.trim()
- String.replaceAll()
- String.startsWith()
- replaceWith()
- String.indexOf()
- replaceAll() with regex
- Check if String is Number
- Check string contains spaces
- Convert String to Boolean
- Check String contains Substring
- Compare Strings
- Math.acos()
- Math.abs()
- Math.asin()
- Math.atan()
- Math.cbrt()
- Math.ceil()
- Math.cos()
- Math.floor()
- Math.fround()
- Math.hypot()
- Math.log()
- Math max()
- Math.power()
- Math.random()
- Math.toRadians()
- Nested Function
- Arrow Function
- Optional Parameters
- The arguments Object
- Calling Vs Invoking a Function
- Call a function every second
- Using function as Values
- Chaining Functions
- if statement
- Handling Special Characters
- hide() Method
- Set.add()
- Remove Element from Set
- DOM Selector Methods
- Find Elements in DOM
- Remove DOM Element
- Replace DOM Element
- Get DOM Element Width
- addEventListener()
- querySelector()
- getBoundingClientRect()
- NodeList
- Node.insertBefore()
- Event Bubbling
- Parse JSON File
- Parse YAML File
- Parse CSV File
- async function
- await
- Exponentiation (**)
- Bitwise XOR (^)
- Nullish Coalescing Operator (??)
- Double Exclamation Mark (!!)
- Spread Operator (. )
- Destructuring assignment
- instanceof Operator
- Access map with index
- Check map size
- Sort map by value
- Sort by date
- Add days to date
- date/time field value out of range
- Promise Thenable Object
- Promise.all()
- Promise.resolve()
- Promise.race()
- Promise.reject()
- Chaining Promises
- Keyboard Events
- Mouse Events
- Singleton Pattern
- Mediator Pattern
- Observer Pattern
- Factory Pattern
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