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

How to Prevent Chrome Tab Flashing When Opening Background Tabs in JavaScript?

Linda Hamilton
Release: 2024-11-07 13:02:02
Original
282 people have browsed it

How to Prevent Chrome Tab Flashing When Opening Background Tabs in JavaScript?

Simulating Background Tab Opening to Avoid Chrome Flashing

In JavaScript, opening a new tab while maintaining focus on the current tab can be achieved using the following code:

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

However, this method causes a brief flicker of the new tab in Chrome. To avoid this issue, consider using the following approach:

Simulating Key Combinations

Chrome supports opening tabs in the background through specific key combinations. You can simulate these combinations using JavaScript and programmatically open background tabs.

The code below demonstrates simulating a Ctrl click event on a dynamically created element:

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

By invoking this function, you can open a new page in a background tab without causing the annoying flicker.

Note: This approach has been tested only in Chrome.

The above is the detailed content of How to Prevent Chrome Tab Flashing When Opening Background Tabs in 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