Home  >  Article  >  Web Front-end  >  How to Prevent Chrome Tab Flashing When Opening Background Tabs in JavaScript?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-07 13:02:02211browse

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();

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);
}

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!

Statement:
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