Url Hashtags and Redirecting

Home / Url Hashtags and Redirecting

Here’s something I learned about Url hashtags a while back that seemed worth sharing.

As you may know, hashtags are never sent to the server. There is, by regular browser redirection, no way to get hashtag information to the server.

For a client-side script based web application that uses hashtags, obviously, this presents a challenge. Even if all you want is a redirect url on login, it can’t utilize the hashtag.

One work-around that I found that works well is to redirect to a page that has a hidden HTML input which you can stuff the hash (url encoded) into and then post that as a named/value pair to the server.

The basic premise was that I changed the ASP.NET login url to point to a “redirect interceptor” MVC controller action. In the view, I just have script that runs on document ready. Once the RedirectUrl or Hashtag are parsed out, and added to the ReturnUrl, the regular Logon controller action is loaded via setting window.location. This is possible because Hashtags survive across 302 redirects. Using this mechanism, there can be almost any sort of complex hashtag preserved.

$(function () {
	var location = '';
	var hasHash = window.location.hash || window.location.toString().toLowerCase().indexOf('#') !== -1;
	var hasReturnUrl = window.location.toString().toLowerCase().indexOf('returnurl') !== -1;

	if (hasReturnUrl && !hasHash) {
		location = '@logonUrl?' + window.location.toString().toLowerCase().split('?')[1];
	else if (hasHash) {
		var returnUrl = window.location.hash.replace('#', '%23');
		returnUrl = returnUrl.split('&').join('%26');
		location = '@logonUrl' + '?returnurl=' + '@DefaultRedirectUrl' + returnUrl;
	else {
		location = '@logonUrl';

	window.location = location;

Leave a Reply