Home > Web Front-end > JS Tutorial > How Can I Open URLs in New Tabs Instead of Pop-up Windows Using JavaScript?

How Can I Open URLs in New Tabs Instead of Pop-up Windows Using JavaScript?

Linda Hamilton
Release: 2024-12-25 18:20:10
Original
207 people have browsed it

How Can I Open URLs in New Tabs Instead of Pop-up Windows Using JavaScript?

Opening URLs in New Tabs Without Pop-up Windows

When attempting to open a URL in a new tab, many developers encounter the issue of the browser opening a pop-up window instead. Despite using code snippets such as window.open(url, '_blank'); and window.open(url);, the desired behavior is not achieved.

Solution

To resolve this problem, a clever technique can be employed:

function openInNewTab(url) {
  window.open(url, '_blank').focus();
}

// Or just
window.open(url, '_blank').focus();
Copy after login

This code focuses the newly opened tab, ensuring that the browser opens the URL in a tab rather than a window.

To utilize this solution effectively, it's recommended to implement it directly in the onclick handler for the link. This prevents pop-up blockers and the default "new window" behavior.

<div onclick="openInNewTab('www.test.com');">Something To Click On</div>
Copy after login

Reference

For further details, refer to the resource: "Open a URL in a new tab using JavaScript."

The above is the detailed content of How Can I Open URLs in New Tabs Instead of Pop-up Windows Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template