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