C#判斷瀏覽器功能實(shí)例詳解
C#判斷瀏覽器是否支持JavaScript和Cookies許多網(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頁面的寫法。
C#判斷瀏覽器功能的分析和解決:
我們首先用 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﹥
C#判斷瀏覽器程序能實(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)閉了。以后要做什么就不用我說了吧?
C#判斷瀏覽器功能的程序內(nèi)容就向你介紹到這里了,希望對(duì)你了解和學(xué)習(xí)C#判斷瀏覽器方面有所幫助。
【編輯推薦】