Skip to content

Instantly share code, notes, and snippets.

@sxtxixtxcxh
Forked from jimeh/redirect_to.coffee
Created March 9, 2010 23:36
Show Gist options
  • Save sxtxixtxcxh/327294 to your computer and use it in GitHub Desktop.
Save sxtxixtxcxh/327294 to your computer and use it in GitHub Desktop.
/*
Handy url redirection that's as flexilbe as the href attribute of A tags.
There might have been an easier way to do this, if so, let me know how stupid
I am :)
Example:
*** Browser is on http://my.domain.com:3000/hello/world.html
window.redirect_to("world2.html"); // => http://my.domain.com:3000/hello/world2.html
window.redirect_to("/blog"); // => http://my.domain.com:3000/blog
window.redirect_to("http://www.google.com/"); // => http://www.google.com/
*/
window.redirect_to = function(url, location){
if (typeof(location) === "undefined") {
location = window.location;
};
var redirect_to = "";
if (url.match(/.+\:\/\/.+/) === null) {
redirect_to += location.protocol + "//";
redirect_to += location.hostname;
if (location.port !== "") { redirect_to += ":" + location.port; };
if (url.charAt(0) !== "/") {
redirect_to += location.pathname.substr(0, location.pathname.lastIndexOf("/")+1);
};
window.location.href = redirect_to + url;
} else {
window.location.href = url;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment