2016-11-17 46 views
3

我希望你能幫助我解決我的問題。我的靜態html網站上有3種語言。我想根據他們的瀏覽器語言設置重定向用戶。靜態多語言javascript重定向不斷重新加載頁面

這是我的代碼:

var lang = navigator.language; 
if (lang == 'pl'){ 
    document.location.href = 'index_pl.html'; 
} 
else if (lang == 'fr'){ 
    document.location.href = 'index_fr.html'; 
} 
else { 
    document.location.href = 'index.html'; 
} 
alert(lang); 

的問題是每次用戶進入網站的這個腳本不斷刷新/重定向一個網站。我的問題是如何檢查一次用戶瀏覽器,然後將用戶重定向到專用網頁。

在此先感謝。

回答

2

如果您不希望它繼續重定向,則需要檢查當前URL中的頁面。例如:

var lang = navigator.language; 
var redirectURL = 'index.html'; 

if (lang == 'pl'){ 
    redirectURL = 'index_pl.html'; 
} else if (lang == 'fr'){ 
    redirectURL = 'index.html'; 
} 

if (document.location.pathname.indexOf(redirectURL) == -1) { 
    document.location.href = redirectURL; 
} 

這將檢查redirectURL是否不在路徑中。

+0

感謝您的回答。所有文件都是根目錄,上面的代碼是檢查用戶瀏覽器語言是什麼,並根據該信息重定向到特定頁面。一旦用戶被重定向,scipt會再次檢查用戶語言。 (無限循環)。也許我應該在第一次重定向之後向url添加內容或者使用localstorage? – Kamil

+0

如果您想存儲選項,您可以使用localstorage或cookie,但不需要。如果仍然重定向,則某些內容與路徑檢查不匹配。註釋掉document.location.href和output(alert或console.log)顯示的內容。例如:alert(document.location.path +「!= /」+ redirectURL) – fanfavorite

+0

返回Undefinded!= /index_pl.html 但是所有文件都在同一個根目錄下 – Kamil

0

嗨,大家好,我想我已經使用localStorage解決了這個問題。下面 代碼:

 if (localStorage.getItem("visit") == null) 
{ 
    // Show Welcome message 
    var lang = navigator.language; 
    if (lang == 'pl'){ 
     document.location.href = 'index_pl.html'; 
    } 
    else if (lang == 'fr'){ 
     document.location.href = 'index_fr.html'; 
    } 
    else { 
     document.location.href = 'index.html'; 
    } 
} 

localStorage.setItem("visit", new Date()); 

可否請你告訴我,如果我是正確的?在此先感謝

+0

此解決方案的問題在於,您將日期設置爲重定向後設置日期。我仍然認爲你不需要這個。你可以看到我修改後的解決方案來檢查字符串中redirectURL的實例,所以它可以在你的本地主機上運行。這種類型的方法也適用,但您需要在重定向之前設置該項目。你可以把它作爲if語句中的第一項。 – fanfavorite