2011-11-04 67 views
1

我有需要强制执行的https我的网站上一些相对链接,即使当前页面是http(所以我不能只用//链接)。jQuery来获取/设置HREF协议

我猜有jQuery的一个非常简单的方法来检索后点击HREF,然后设置页面位置,以匹配被点击前缀使用HTTPS协议的链接?

在此先感谢!

回答

1

你需要一个URL加入辅助功能(下面一个从another answer修改我放弃)。完整的代码,假设你添加class="httpsLink"的特殊<a>链接:

var urlJoin = function(base, relative) 
{ 
    // See if there is already a protocol on this 
    if (relative.indexOf("://") != -1) 
     return relative; 

    // See if this is protocol-relative 
    if (relative.indexOf("//") == 0) 
    { 
     var protocolIndex = base.indexOf("://"); 
     return base.substr(0, protocolIndex+1) + relative; 
    } 

    // We need to split the domain and the path for the remaining options 
    var protocolIndexEnd = base.indexOf("://") + 3; 
    if (base.indexOf("/", protocolIndexEnd) == -1) // append slash if passed only http://bla.com 
     base += "/"; 
    var endDomainIndex = base.indexOf("/", protocolIndexEnd); 
    var domain = base.substr(0, endDomainIndex); 
    var path = base.substr(endDomainIndex); 
    if (path.lastIndexOf("/") != path.length-1) // trim off any ending file name 
     path = path.substr(0, path.lastIndexOf("/")+1); 

    // See if this is site-absolute 
    if (relative.indexOf("/") == 0) 
    { 
     return domain + relative; 
    } 

    // See if this is document-relative with ../ 
    while (relative.indexOf("../") == 0) 
    { 
     relative = relative.substr(3); 
     if (path.length > 1) 
     { 
      var secondToLastSlashIndex = path.substr(0, path.length-1).lastIndexOf("/"); 
      path = path.substr(0, secondToLastSlashIndex+1); 
     } 
    } 
    // Finally, slap on whatever ending is left 
    return domain + path + relative; 
}; 

$('a.httpsLink').click(function(e){ 
    e.preventDefault(); 
    location.href = urlJoin(location.href, $(this).attr('href')).split('http://').join('https://'); 
}); 

这将与任何类型的环节的工作,无论是绝对或相对的。

+0

这是唯一完美解决方案 - 很高兴! –

4

要获取协议:

document.location.protocol; 

设置协议:

document.location.protocol = 'https:'; 
+0

在Firefox(25)中设置协议会导致错误。 – Amunak

1

如果你得到的所有链接的页面(不太可能),你可以使用一个全球性的选择上:

$('a').click(function(e) { 
    location.href = this.attr('href').replace("http://", "https://"); 
}); 

如果你需要更多的选择性,可以应用自定义类选择只得到某一些(这个类就牛逼母鸡都被应用到这些链接):

$('.outsideLinkClass').click(function(e) { 
    location.href = this.attr('href').replace("http://", "https://");  
}); 

编辑: 重新阅读我的回答一点之后,它发生,我认为简单的更换,如果你使用的内部链接选项可能无法正常工作这是基于相关的网址。在这种情况下,您需要更多地参与分配代码,以确保您正在修改完整的url并且不仅仅信任替换。

编辑2: 一个更强大的协议更换一个想法:

$('.outsideLinkClass').click(function(e) { 
    var baseUrl = window.location.pathname.substring(0, window.location.pathname.indexOf('/')); 
    location.href = baseUrl.replace("http://", "https://") + this.attr('href'); 
}); 

上面的代码是未经测试,所以你可能会不得不调整来分配baseUrl变量做正确的路线,但是这应该使它成为可能。

+0

乔尔,你有什么看起来像它会工作,但正如你所说的,因为我使用相对URL,我需要this.attr(“href”属性),并在前面加上协议和域 - 任何想法如何做到这一点? –

+0

@ Al.-Edit发布新的伪代码。 –

+0

乔尔,对不起,它没有奏效 - baseURL空着。下面的解决方案看起来非常广泛,并且完美地工作,所以我就这样做了非常感谢您的回复! –