To improve performance on some bulky web apps, I've created an update that converts them to single-page apps. Only JS / jQuery are in use; thus far, it hasn't seemed useful to introduce Angular, React, Meteor, etc. However, beta testing has revealed a problem, which is that (duh) sometimes a user will want to open something in a new tab / window. The interactive elements in question are currently anchors with no href
attribute, so it is not currently possible to open in a new tab.
My understanding is that if I were to use an a
with an href
and preventDefault()
, users would still not be able to open in a new tab.
I considered placing "open in new tab" checkboxes next to the interactive elements, and I considered some other approaches that would require people to learn new, idiomatic interaction patterns. Bad idea.
Now, I'm thinking that I'll try using the onbeforeunload
event handler to prevent changing the current window's location and instead affect the desired changes to the current screen. I believe this would not prevent opening in a new tab, since doing opening in a new tab won't fire the unload event.
I can't be the first person to try to address this problem, but I can't find any info on it, either. Anyone know how to prevent opening in the same tab while allowing opening in a new tab and while not forcing people to learn new interaction patterns? Anyone have a reason to believe that using the onbeforeunload
event handler will not allow me to achieve that?
Update
In case it helps anyone in the future, below is what I developed. Thanks to @Kiko Garcia; it hadn't occurred to me that one could detect which mouse button was used. Tested on Firefox 54, Chrome 57, Edge, IE 11 (all on Windows 10) and on Safari for iOS10 and on Android Browser for Android 7. (Will test on Mac next week, but assuming it's good for now.)
// track whether or not the Control key is being pressed
var controlKeyIsPressed = 0;
$(document).keydown(function(keyDownEvent) {
if(keyDownEvent.which == "17") {
controlKeyIsPressed = 1;
}
});
$(document).keyup(function(){
controlKeyIsPressed = 0;
});
// on clicking anchors of the specified type
$("a.some-class").on("click", function(clickEvent) {
// left click only
if (clickEvent.which == 1 && controlKeyIsPressed == 0) {
// prevent default behaviour
clickEvent.preventDefault();
// perform desired changes on this screen
// middle click
} else if (clickEvent.which == 2) {
// prevent default behaviour because behaviour seems to be inconsistent
clickEvent.preventDefault();
}
});