Have a link that uses window.history by default but still supports opening in new tab

Viewed 49

Say my website is example.com. On it, I have the following link: <a href="?foo=bar">Click here</a>, which upon clicking should take the user to example.com/?foo=bar.

What I want is, by default, the link should use window.history when clicked. In particular, it will use

window.history.pushState({"foo": "bar"}, "", "?foo=bar")

However, if the user e.g. "middle clicks" or right clicks and says "Open in New Tab", then the anchor link should act as normal and just open in a new tab (without erroneously triggering the pushState in the current tab). This should also preferably work with non-standard methods of opening a link in a new tab, such as using the Vimium web extension.

Is there some standard way of accomplishing this?

1 Answers

I wrote a demo. href is used for the right clicks and e.preventDefault() is for the default action

    <div>
        <a href="?foo=bar" id="testLink" >Jump</a>
    </div>
    <script>
        window.onload = function () {
            document.querySelector('#testLink').addEventListener('click', function(e) {
                e.preventDefault()
                window.history.pushState({"foo": "bar"}, "", "?foo=bar")
            })
        }
    </script>

Related