将显式协议规范与相对 URL 相结合
我有一个通过 HTTP 访问的页面。此页面使用 HTTPS 链接到同一服务器上的另一个页面。在使用相对 URL 的同时,使用 HTML 和/或 Javascript 强制转换到 HTTPS 的最优雅的方式是什么?
基本上,我想要 协议相关 URL。我想显式指定 HTTPS,而不将主机名硬编码到 URL 中。
我正在开发一个大型旧网站,因此使用不显眼的 javascript 并对现有标记进行最小更改的解决方案是理想的。
我意识到在目标页面上强制执行 HTTPS 效果更好,但在本例中这不是一个选项。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以提供一个更具体的选择器,以确保它不会弄乱您不打算更改的任何链接,但我将其留给您,因为您知道要求。
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.
我认为您必须根据
window.location
上的片段自行构建 URL。或类似的东西(特别是如果有参数等)。
编辑 - 人们注意到,当您访问“href”值时,现代浏览器将返回完整的 URL,这使得在这些情况下更容易解决问题(因为您只需修复协议前缀)。 (谢谢@丹尼尔!)
I think you're going to have to build the URL yourself from the pieces on
window.location
.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!)