Skip to content

Instantly share code, notes, and snippets.

@jimeh
Created March 9, 2010 22:34
Show Gist options
  • Save jimeh/327227 to your computer and use it in GitHub Desktop.
Save jimeh/327227 to your computer and use it in GitHub Desktop.
redirect_to.js: Handy url redirection that's as flexilbe as the href attribute of A tags.
###
Handy url redirection that's as flexible 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 "#item/42"
// => http://my.domain.com:3000/hello/world.html#item/42
window.redirect_to "http://www.google.com/"
// => http://www.google.com/
window.redirect_to "/go/to?url=http://www.google.com/"
// => http://my.domain.com:3000/go/to?url=http://www.google.com/
###
window.redirect_to = (url, location) ->
redirect_to = ""
location = window.location if typeof(location) == "undefined"
if url.charAt(0) == '#'
redirect_to += location.href.split('#')[0]
window.location.href = redirect_to + url
else if url.match(/^[a-zA-Z]+\:\/\/.+/) == null
redirect_to += location.protocol + "//" + location.hostname
redirect_to += ":" + location.port if 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
/*
Handy url redirection that's as flexible 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("#item/42");
// => http://my.domain.com:3000/hello/world.html#item/42
window.redirect_to("http://www.google.com/");
// => http://www.google.com/
window.redirect_to("/go/to?url=http://www.google.com/");
// => http://my.domain.com:3000/go/to?url=http://www.google.com/
*/
window.redirect_to = function(url, location){
var redirect_to = "";
if (typeof(location) == "undefined") location = window.location;
if (url.charAt(0) === '#') {
redirect_to += location.href.split('#')[0];
window.location.href = redirect_to + url;
} else if (url.match(/^[a-zA-Z]+\:\/\/.+/) === null) {
redirect_to += location.protocol + "//" + 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