I'm trying to use javascript to determine if a user's browser has cookies enabled or not.
To test: copy this code into a file with a 'html' extension, and load it into your IE browser directly, through a local web server and through a remote web server.
By turning cookies on/off in your browser, running the file, then clicking the 'test1' or 'test2' buttons, the displayed text should accurately inform you if your cookies are On or Off.
FireFox behaves as expected, but IE 6 does not (surprised?).
When this script below is run from an external server, it works on IE.
But if I simply load the page 'locally' in my IE browser (drag-n-drop or File>Open), it sees that cookies are turned off. As well, if I load it via IIS on an internal network, it never sees that cookies are turned off.
It's as though it must only come from an external server to work - why?
How can I make it work in IE 6 regardless of where the page came from?
Thanks....
Expand|Select|Wrap|Line Numbers
- <html>
- <input type="button" value="test1" onclick="javascript:test1();">
- <input type="button" value="test2" onclick="javascript:test2();">
- <input type="button" value="kill all" onclick="javascript:killAll();">
- <div name="test" id="test"></div>
- <script language="JavaScript">
- function killAll(){
- killCookie('test1');
- killCookie('test2');
- document.getElementById("test").innerHTML='';
- }
- function killCookie(cookieName){
- if(document.cookie.indexOf(cookieName)!=-1){
- document.cookie=cookieName+"=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
- }
- }
- function test1(){
- var cookieName='test1';
- killCookie(cookieName);
- document.getElementById("test").innerHTML='';
- var today=new Date();
- var expire=new Date();
- expire.setTime(today.getTime()+60000);
- document.cookie=cookieName+"=;expires="+expire.toGMTString();
- if (document.cookie.indexOf(cookieName)!=-1){
- document.getElementById('test').innerHTML='<b>test1=Cookies are currently enabled in your browser.</b>';
- }else{
- document.getElementById('test').innerHTML='<b>test1=Cookies are NOT currently enabled in your browser.</b>';
- }
- }
- function test2(){
- var cookieName='test2';
- killCookie(cookieName);
- document.getElementById('test').innerHTML='';
- document.cookie=cookieName;
- if (document.cookie.indexOf(cookieName)!=-1){
- document.getElementById('test').innerHTML='<b>test2=Cookies are currently enabled in your browser.</b>';
- }else{
- document.getElementById('test').innerHTML='<b>test2=Cookies are NOT currently enabled in your browser.</b>';
- }
- }
- </script>
- </html>