2011-11-04 26 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空着。下面的解決方案看起來非常廣泛,並且完美地工作,所以我就這樣做了非常感謝您的回覆! –