如何在源代码中使用JavaScript将每个http更改为https?

如何在源代码中使用JavaScript将每个http更改为https?,javascript,http,https,Javascript,Http,Https,我想使用JavaScript将http的每个实例都更改为https。我该怎么做?源代码是什么样子的?您可以在JavaScript中将http流量重定向到https,如下所示: <script type="text/javascript"> <!-- begin hide function httpsRedirect() { var httpURL = window.location.hostname + window.location.pathname; var httpsU

我想使用JavaScript将http的每个实例都更改为https。我该怎么做?源代码是什么样子的?

您可以在JavaScript中将http流量重定向到https,如下所示:

<script type="text/javascript"> 
<!-- begin hide
function httpsRedirect()
{
var httpURL = window.location.hostname + window.location.pathname;
var httpsURL = "https://" + httpURL;
window.location = httpsURL; 
}
httpsRedirect();
// end hide -->;
</script>

;

无论如何,我假设您所追求的是标签,但这应该很容易推广到其他人:

if (document.location.protocol === 'https:') {
    $('a').each(function() {
        var href = $(this).attr('href');
        if (href.indexOf('http:') > -1) {
            href = href.replace('http:', 'https:');
            $(this).attr('href', href);
        }
    });
}

您可以在http域页面中向servlet抛出https更改请求,服务器将重定向到https域页面。试图在javascript中将域从http更改为https将导致浏览器安全错误(因为在所有现代浏览器中跨域请求都被拒绝)。 我解决了如下所示的相同问题

function readyForSecure(loginID)
{
   if (location.protocol == 'http:') {
   // https change request
      HTMLFormElement.prototype.submit.call(document.getElementById('login-box'));
   }
}


<form id="login-box" action='xxxxxx' method="post" accept-charset="UTF-8">
   ...
   <input type="button" value="Login"  onfocus="readyForSecure(this.value)"/>
</form>
函数readyForSecure(loginID)
{
如果(location.protocol==“http:”){
//https更改请求
HTMLFormElement.prototype.submit.call(document.getElementById('login-box');
}
}
...

你可以在这里查阅

你为什么要这么做?只需在浏览器中关闭JS即可禁用通过JS更改任何内容。如果要强制站点/应用程序将所有链接更改为使用SSL,则应在服务器上的源代码中执行此操作,或者如果是在Apache上,则可以使用.htaccess文件重定向。