Home > Web Front-end > JS Tutorial > body text

How Can I Open a New Tab in the Background from JavaScript Without a Flash?

Barbara Streisand
Release: 2024-11-07 14:47:02
Original
745 people have browsed it

How Can I Open a New Tab in the Background from JavaScript Without a Flash?

Can I Open a New Tab in the Background While Staying on the Current Tab?

When working with JavaScript, it is possible to open a new page in a different tab while staying focused on the current tab using the following code:

open('http://example.com/');
focus();
Copy after login

However, this approach may cause a momentary flash of the new tab before switching back to the current tab in Chrome. To avoid this issue, a more sophisticated method is required.

Solution: Simulating Key Events

This solution involves simulating a key combination (e.g., Ctrl click) on a dynamically generated element to create a background tab. The following code accomplishes this:

function openNewBackgroundTab(){
    var a = document.createElement("a");
    a.href = "http://www.google.com/";
    var evt = document.createEvent("MouseEvents");
    // Simulate Ctrl key press
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
    a.dispatchEvent(evt);
}
Copy after login

This method works by creating an element, setting its href attribute to the desired URL, and then dispatching a click event with the "Ctrl" key simulated. This results in a background tab being opened without affecting the focus of the current tab.

The above is the detailed content of How Can I Open a New Tab in the Background from JavaScript Without a Flash?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!