判斷客戶端是否支持JavaScript與Cookies
來源:程序員人生 發(fā)布時(shí)間:2013-12-07 02:51:46 閱讀次數(shù):2675次
許多網(wǎng)站需要客戶端做許多復(fù)雜的工作,比如:用客戶端 JavaScript 進(jìn)行數(shù)據(jù)合法性校驗(yàn),這需要客戶瀏覽器的
JavaScript enabled;使用 Session 變量記錄身份等信息,需要瀏覽器 Cookies enabled。因此,有必要確定用戶瀏覽器
中的這些選項(xiàng)被打開。在我的網(wǎng)站中,我使用了一串簡(jiǎn)潔的代碼實(shí)現(xiàn)這些功能,在用戶登錄時(shí)進(jìn)行檢查,如果不符合就不
讓登錄。在本文中,我就介紹一下這個(gè)login頁面的寫法。
我們首先用 JavaScript 建立一個(gè) Cookie,然后檢查 Cookie 是否存在。由于我們使用 JavaScript 進(jìn)行這項(xiàng)操作,如果
用戶沒有打開 JavaScript,但打開了 Cookies 的話,我們?nèi)匀粫?huì)得到 Cookies 沒打開的結(jié)果。但這與我們的要求并不沖
突,反正我們是要求兩者都打開的。(如果你確實(shí)只想知道 Cookies 是否 enabled,而不關(guān)心 JavaScript,也是有辦法
的,我們?cè)诹砦闹杏懻摚┮_定用戶是否打開 JavaScript,我在 html 中建立了一個(gè)隱藏 from,然后在 onload 事件中
調(diào)一個(gè) JavaScript 函數(shù),改變?cè)撾[藏 form 的值,如果值被改變了,那就說明 JavaScript 是打開的,否則這個(gè)
JavaScript 函數(shù)就不會(huì)被調(diào)用。(上面兩個(gè)功能我寫在一個(gè)函數(shù)中)
首先,我們放一個(gè)隱藏 form 在 html 中,用<form>...</form>括起來。(當(dāng)然,中間還可以有 username/password 的
from)
<FORM>
...
<input type="hidden" name="cookieexists" value="false">
</FORM>
只要它的值是false,就說明瀏覽器不支持 JavaScript。注意其初始值是 false。我們的 JavaScript 函數(shù)將把這個(gè)值換
為true。在 BODY 中這樣寫:
<body onload="cc()">
cc()的內(nèi)容如下:
<script language="JavaScript">
<!-
function cc()
{
/* check for a cookie */
if (document.cookie == "")
{
/* if a cookie is not found - alert user -
change cookieexists field value to false */
alert("COOKIES need to be enabled!");
/* If the user has Cookies disabled an alert will let him know
that cookies need to be enabled to log on.*/
document.Form1.cookieexists.value ="false"
} else {
/* this sets the value to true and nothing else will happen,
the user will be able to log on*/
document.Form1.cookieexists.value ="true"
}
}
/* Set a cookie to be sure that one exists.
Note that this is outside the function*/
document.cookie = 'killme' + escape('nothing')
// -->
</script>
這個(gè)程序能實(shí)現(xiàn)的功能是:
1 當(dāng)用戶 JavaScript 打開,而 Cookies 關(guān)閉時(shí)彈出警告信息
2 當(dāng)用戶 JavaScript 關(guān)閉,用戶無法直接得到檢查結(jié)果。(不要忘記,要彈出警告窗口也需要執(zhí)行 alert 這個(gè)
JavaScript 語句,這時(shí)即使檢查出來都無法提示),但這時(shí)用戶的 from 提交后,后臺(tái)的程序就會(huì)發(fā)現(xiàn) cookieexists 這
個(gè)域的值是 false,這就說明 JavaScript 關(guān)閉了。以后要做什么就不用我說了吧?
翻譯:討飯貓
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)