Combine explicit protocol specification with relative URL
I have a page that is accessed via HTTP. This page links to another page on the same server using H开发者_JAVA技巧TTPS. 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").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.
I think you're going to have to build the URL yourself from the pieces on window.location
.
var path = anchor.href;
var httpsUrl = "https://" +
window.location.host +
(path.charAt(0) === '/' ? path : window.location.pathname + '/' + path);
or something like that (esp. if there's are parameters etc).
edit — it's been noted that modern browsers will give back the complete URL when you access the "href" value, making this an even easier problem to solve in those cases (as you just have to fix the protocol prefix). (Thanks @Daniel!)
精彩评论