It is possible to use <link>
as
<Link to="route" target="_blank">
to open links in new tab. But is it possible to use browserHistory.push
to open links in a new tab?
React-router is build on the browser History API.
browserHistory.push
calls pushState()
method.
From the first line of the linked document:
pushState( ) takes three parameters: A state object, a title (which is currently ignored), and (optionally) a Uniform Resource Locator (URL).
So, the answer to your question is "No".
I've been grouching about it for an hour until I saw Cooper's comment
browserHistory is per tab.
which is so simple but accurate, and made me come up with this solution:
I put it in my App.js (UPDATE: I've added the window blur
event because I've encountered a missing keyUp event when cmd+tab or cmd+` to another window.)
const [metaKeyPressed, setMetaKeyPressed] = useState(false);
const handleMetaKeyDown = e => {
if (e.metaKey) {
setMetaKeyPressed(true);
}
};
const handleMetaKeyUp = e => {
if (e.metaKey) {
setMetaKeyPressed(false);
}
};
useEffect(() => {
document.addEventListener('keydown', handleMetaKeyDown);
document.addEventListener('keyup', handleMetaKeyUp);
window.addEventListener('blur', handleMetaKeyUp);
return () => {
document.removeEventListener('keydown', handleMetaKeyDown);
document.removeEventListener('keyup', handleMetaKeyUp);
window.removeEventListener('blur', handleMetaKeyUp);
};
});
Then I have metaKeyPressed
which I use to select whether to history.push
or window.open
(simplified for readability):
const handleRoute = path => {
if (metaKeyPressed) {
window.open(path);
} else {
history.push(path);
}
};
Also, Consider adding a fix for this issue https://www.jitbit.com/alexblog/256-targetblank---the-most-underestimated-vulnerability-ever/ I haven't not add this because the browser wants the user to explicitly allow popups when I do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With