If a user is on your website and opens another link (also to your website) in a new tab, is it possible to differentiate this from the user just clicking on the link normall
It is client behaviour, so I think you could do something with javascript, like check for browser history, but it is ambiguous between a new tab and a new windows.
Beside that, not all browsers has tabs and not all browsers has the same meaning for what a tab is (in some are different process, in some others they aren't).
But, why would you want to check that? It really matter if your application is executing in a new tab or not? I don't think so...
I really don't think so. The closest you could get as far as I'm aware of is monitoring keypress and mouseclick events to try to match actions to common methods for opening links in new tabs. (ie. if they're holding Command when they click, or middle-clicked, it's probably a new tab). That wouldn't be reliable though, as any of those bindings can be changed.
You can sort of do it like this:
if (history.length == 1) { // Um, needs to be 0 for IE, 1 for Firefox
// This is a new window or a new tab.
}
There may be other ways for history.length
to be 1
, but I don't know what they might be.
The window.opener property in JavaScript will point to the window that opened the new window. However it doesn't distinguish between a new window and a new tab. Tabs are not part of the official W3C spec so there's no direct support for them.
In addition to history.length in JavaScript you can read/write the window's name.
Thus if you check if it has a name onload... it should be blank on the very first load... if you then set it to "foo"... on each subsequent load in that window... the window.name property will return "foo"... unless you open a link in a new tab/window... that new window should have no name set.
(unless of course you open a popup via window.open(url, name, features); which allows you to pre-set the name)
<script>
if(window.name == ''){
//first load (or Nth load in a new Tab/Window)
if(!SOME_VALUE_SET_FOR_2ND_TO_NTH_LOADS){
//set name so we can catch new Tab/Window
window.name = 'myWinName';
} else {
//we have a new Tab/Window (or something funky)
alert('What?! One window not cool enough for ya?\n' +
'Calling the InterWeb Police!');
}
} else if(window.name == 'myWinName'){
//2nd-Nth load
document.title = 'All is well... we think';
}
</script>
Caveats:
This is what I use in ASP.NET MVC to forbid authenticated users to open multiple tabs:
<script language="javascript" type="text/javascript">
@if(Request.IsAuthenticated)
{
<text>
if (window.name != 'singleWindow') {
window.location.href = "Content/ErrorPages/SingleTab.htm";
}
</text>
}
else
{
<text>
window.name = "singleWindow";
</text>
}
</script>
Basically, this sets the window name first time when the user visits the login page. After logging in, for each subsequent page load the window name is tested.
Two problems: