views:

55

answers:

2

I have a page that is accessed via HTTP. This page links to another page on the same server using HTTPS. What is the most elegant way, using HTML and/or Javascript, to force a transition to HTTPS while using a relative URL?

Basically, I want the opposite of a protocol-relative URL. I want to explicitly specify HTTPS WITHOUT hardcoding the hostname into the URL.

I'm working on a large legacy site so a solution using unobtrusive javascript with minimal changes to existing markup is ideal.

I realize that enforcing HTTPS is better performed at the destination page, but that isn't an option in this case.

A: 
Pointy
Yeah, I've pretty much accepted that. I was just hoping someone could point out a library or jquery plugin or something that turned that into a one-liner. It's not hard to build, but if someone's already been through all the edge cases and identified a clean, unobtrusive way of wiring it up.....
Seth Petry-Johnson
I don't think this would work. `anchor.href` is resolved to the full URL even if the provided href was a relative URL.
CD Sanchez
@Daniel that's true in modern browsers, making this even easier to do, but not true in old versions of IE. Before IE8, you'd get back whatever was authored into the attribute in the original markup.
Pointy
@Pointy: Thanks! Good to know. I don't have any old browsers installed (ignorance is bliss as they say). Do you know if the `anchor.pathname` property is automatically resolved in older browsers for relative URLs? I would assume so -- if so, you can let the browser do some of the work and remove that conditional logic for the relative URLs.
CD Sanchez
@Daniel I don't remember exactly - that kind of thing is not something I've really had to deal with very much, so most of what I know is from stuff I've read here and there, and a small amount of random experience.
Pointy
FWIW `.href` returns the fully qualified url consistently, even in old IEs. You're thinking of `.getAttribute('href')` which by spec should return the value set in source, but IE forces you to pass in a magic second argument to it in order to get the raw attribute value.
Crescent Fresh
Hmm OK @Crescent Fresh, thanks for the clarification!
Pointy
A: 
$("a").each(function () { 
    this.href = "https://" + window.location.host + this.pathname + this.search + this.hash;
});

You could provide a more specific selector to make sure it doesn't mess up any links you didn't intend to change, but I leave that up to you since you know the requirements.

CD Sanchez