Solved

captureing browser close (x) button click in Fairfox3

Posted on 2008-11-02
33
2,110 Views
Last Modified: 2013-12-13
I need to pop up a survey window when the user closes the browser.
Means when the user clicks on the (x) button of the browser.
I wrote some javascript code for capturing the above event . its working in well in IE.
But its not working in Fairfox3.0. I have been working on this for the last 3 days.
and I tried so many different ways using javascript. But its not working in fairfox 3.

Here is my code

if (event.ClientX > document.client.width  && event.ClientY <0 )
    {
           window.open (surveywindow.aspx)
    }
The above code is working well in internet explorer. But not at all working in FAirfox3.0
This is very very important for me. I appreciate if I could get some help here.

Thanks in advance
0
Comment
Question by:ken_rgr
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 17
  • 16
33 Comments
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22862061
If your trying to display a popup when the page is closed, then you can use the onunload event. But beware, if the client web browser is set to block popups, the window will NOT be shown.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>Demo Page</title>
		<script type="text/javascript">
			window.onunload = function(event) {
				window.open('surveywindow.aspx');
			};
		</script>
	</head>
	<body>
		<h1>Demo Page</h1>
		<div>
		</div>
	</body>
</html>

Open in new window

0
 

Author Comment

by:ken_rgr
ID: 22862204
Onunload event fires even if the user clicks on a hyper link also. or user moves to a different page also I want the pop up should show  only when the user clicks on the browser close button.
Any better solution??
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22862231
Not one that I know of because the position of the close button is both browser and OS specific. Even if you fixed your problem above, if it were viewed on an OS or a custom windows theme, where the X button is in a different place, say at the bottom of the window, your code might not work properly.

Also another major problem is that most browsers these days block popups, especially when a page is about to change.

Here's my advice. Have a nice big button at the top of your page saying "Take Survey - Give us your view" or something to the like. This is nowhere near as annoying to the person viewing your site, a popup everytime they close your site is likely to put them off visiting. Also, a button is fairly standard, and thus you can be assured that it will work the same on pretty much every single browser in circulation.
0
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 

Author Comment

by:ken_rgr
ID: 22862278
I  know the browser close button might be in different places. But my requirement is only when
the user clicks on the close button then only the survey should pop.
but my code works perfectly in IE. then why cant its not working in Fairfox3. ???
and it is possible as I have seen in some web sites when you close the browser it pops up a window.
please check the websit www.kitco.com.
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22862318
Here are some possible reasons why you are having trouble.

Getting the mouse position in FireFox is different to in IE. So your problem might be that the mouse position your getting in FireFox is undefined. You should verify that your actually getting the mouse position.

I use the Prototype framework for JavaScript for this kind of stuff. Prototype provides an approach which works across all major browsers: http://prototypejs.org

In Prototype you can get the mouse pointer position using:
var mouseX = Event.pointerX(event);
var mouseY = Event.pointerY(event);
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22862321
Also, on this computer, the website you linked me to didn't show a popup in IE nor FireFox nor Chrome.
0
 

Author Comment

by:ken_rgr
ID: 22862462
What is prototype. Honestly I am very poor in javascript.
please check my code for farifox.

                 var posx;var posy;
                    posx=0;posy=0;
                    var ev=(!e)?window.event:e;//IE:Moz
                    if (ev.pageX)
                    {//Moz
                        posx=ev.pageX+window.pageXOffset;
                        posy=ev.pageY+window.pageYOffset;
                    }
                alert(posx);
                alert(posy);

The above code gives me x and y coordinates of the page anywhere I click, but it
doesnt return anything when I click above the page i.e browser menu or minimize or maximize or
close button or the taskbar.
0
 

Author Comment

by:ken_rgr
ID: 22862987
Any solution ???
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22863270
Sorry about the delay. I think I have come up with an alternative.

When the page is unloaded, if the user has not clicked within the last second (i.e. hasn't clicked on a link in your website) yet the window is still being closed, the user must have closed the tab, or window.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>Demo Page</title>
		<script type="text/javascript">
			var timeMouseDown = 0;
			function getTimeNow() { return (new Date()).getTime(); }
			window.onmousedown = function(event) {
				timeMouseDown = getTimeNow();
			};
			window.onunload = function(event) {
				var timeNow = getTimeNow();
				if (timeNow - timeMouseDown >= 1000) {
					window.open('http://www.google.com');
				}
			};
		</script>
	</head>
	<body>
		<h1>Demo Page</h1>
		<div>
			<a href="myPage.html">Test Page</a>
		</div>
	</body>
</html>

Open in new window

0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22863289
The previous just works in FF....The following works in FF and IE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>Demo Page</title>
		<script type="text/javascript">
			var timeMouseDown = 0;
			function getTimeNow() { return (new Date()).getTime(); }
			document.onmousedown = function(event) {
				timeMouseDown = getTimeNow();
			};
			window.onunload = function(event) {
				var timeNow = getTimeNow();
				if (timeNow - timeMouseDown >= 1000) {
					window.open('http://www.google.com');
				}
			};
		</script>
	</head>
	<body>
		<h1>Demo Page</h1>
		<div>
			<a href="myPage.html">Test Page</a>
		</div>
	</body>
</html>

Open in new window

0
 

Author Comment

by:ken_rgr
ID: 22863590
Hi
I reallly appreciate your hard work.
I tested your code. But its popping up the google site everytime when I click a link.
I dont want to pop up to show when the user clicks on any link in our website.
I want the pop up to show only when the user leaves our site.
If you check my code in the question it pops up only when the user clicks on browser close
button. I want that kind of functionality in Fairfox.

0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22863779
No worries, if I can help, I will.

That's really strange, because on here when you click "Test Page" it doesn't show the Google popup, but if you close the window it does. Could you confirm that it was the second example that you copied and pasted from here.

If it was the second version you copied, try changing the 1000 to 2000.

Also, what OS are you using?

It sounds like the "onmousedown" event is not getting fired for some reason. If the above fails, try the following source. In the following I have moved the event handler into the body HTML itself. Again, it is actually working on this computer in both IE and FF. If, for some reason, this is not working, try uncommenting the line in the function below to display an alert whenever the mouse button is pressed down. Then try and click on a blank part of the page, the message box should appear.

If it doesn't then there is a problem. If it does show, try and click on the link. The message box should appear prior to going to a "mypage.html" file.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>Demo Page</title>
		<script type="text/javascript">
			var timeMouseDown = 0;
			function getTimeNow() { return (new Date()).getTime(); }
			function body_mouseDown(event) {
				// Uncomment the following line for testing...
				//alert('Mouse button was pressed!'); 
				timeMouseDown = getTimeNow();
			}
			window.onunload = function(event) {
				var timeNow = getTimeNow();
				if (timeNow - timeMouseDown >= 1000) {
					window.open('http://www.google.com');
				}
			};
		</script>
	</head>
	<body onmousedown="body_mouseDown(event||window.event);">
		<h1>Demo Page</h1>
		<div>
			<a href="../inner.html">Test Page</a>
		</div>
	</body>
</html>

Open in new window

0
 

Author Comment

by:ken_rgr
ID: 22864004
I tried your first version . as your said it works in FF.
Now I tried the 2nd version and 3rd version.
both versions working in intervals.
Like for first click its showing the popup. after that few clicks its working fine , not showing
any pop ups. again after some clicks its showing the pop ups. why is this kind of behaviour.
But I dont want to show up the popup until the user leaves out site.
I had a feeling that you are going in the right direcction.
little more help will be  highly appreciated.
I tried to change time from 1000 to 2000. still its showing the popups.
Do you want me change the timing to 5000??. what is this timing, is it milliseconds or seconds.??
and one more thing when I turn on the onmousedown alert its showing the alert properly.
That means on mouse down event is working properly.
Our operating system is window xp professional.
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22865870
Right, I have come up with another approach which seems a lot more consistent, and it does not rely on time!

See how you get on with this, I have another trick up my sleeve if this doesn't work.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>Demo Page</title>
		<script type="text/javascript">
			var g_cancelChange = false;
			document.onmouseout = function(event) {
				g_cancelChange = false;
			}
			document.onmousemove = function(event) {
				g_cancelChange = true;
			}
			window.onunload = function(event) {
				if (!g_cancelChange) {
					window.open('http://www.google.com');
				}
			}
		</script>
	</head>
	<body>
		<h1>Demo Page</h1>
		<div>
			<a href="mypage.html">Test Page</a>
		</div>
	</body>
</html>

Open in new window

0
 

Author Comment

by:ken_rgr
ID: 22867815
Hi The above solution is almost working good. Its not showing any pops when I click on any link.
But its showing popups when I refresh the page or click on back or forward buttons.
And one more thing its changing the size of the font in IE. I guess may be its disabling the CSS.
But it shows properly in FairFox.
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22867888
Yes the refresh thing is a problem, but I'm sorry, I don't know how you can distinguish between hitting refresh and hitting the X.

The example above doesn't change the font size on this computer. There isn't anything in there to cause a font size change. If your font is somehow changing size, it must be related to some other code your using.
0
 

Author Comment

by:ken_rgr
ID: 22867997
I can manage with refresh thing. What about hitting back button or forward button. do you think
anything we can do .

0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22868084
Unfortunately, it's the exact same problem.

Sorry :(
0
 

Author Comment

by:ken_rgr
ID: 22873183
I planning  to use my code for Internet explorer (which works for both and your code for Fairfox.
I tried to merge both of our codes. now your code for fair fox is not working.
Could please check where I am doing mistake ??
In my code I have created a function (SurveyPopup)which checks for cookies. if the cookie avaialable then popup wont show up. Basically we want to generate the survey for only non registered users.
Here is my code.

  <script language="javascript">                                                
                  function getCookie(name)         // Getting cookie name       
                  {                        
                        var dc = document.cookie;
                        var prefix = name + "=";
                        var begin = dc.indexOf("; " + prefix);
                        if (begin == -1)
                        {
                              begin = dc.indexOf(prefix);
                              if (begin != 0) return null;
                        }
                        else
                              begin += 2;
                        var end = document.cookie.indexOf(";", begin);
                        if (end == -1)
                              end = dc.length;
                        return unescape(dc.substring(begin + prefix.length, end));
                  }
                        var surveyCookie1 = getCookie("SelectSurveyNetASPAdvancedCookie");
                        var surveyCookie2 = getCookie("SelectSurveyASPAnonymousUserID");                  
                        var surveyCookie3 = getCookie("AOASURVEY");
                        
                  function SurveyPopup()
                  {      
                      alert(surveyCookie1);
                      alert(surveyCookie2);
                      alert(surveyCookie3);
                      
                      if ((surveyCookie1 == null) && (surveyCookie2 == null) && (surveyCookie3 == null))
                      {
                        Surveywindow=window.open('http://qa.mysite.com/Surveys/TakeSurvey.aspx?SurveyID=n4KH4nm','Survey','center:yes;dialogWidth:900px;dialogHeight:600px');    
                    }
                  }


        <!--
        // For Intetnet Explorer
       
        if (navigator.appName == 'Microsoft Internet Explorer')
        {
            function window.onbeforeunload()  
            {  
                    if( event.clientX>document.body.clientWidth && event.clientY<0 || event.altKey )  
                    {  
                        window.event.returnValue=SurveyPopup();
                 }
             }  
        //-->  
        }            
       // For FairFox  
        else
        {
            var g_cancelChange = false;
            document.onmouseout = function(event)
            {
                  g_cancelChange = false;
            }
            document.onmousemove = function(event)
            {
                  g_cancelChange = true;
            }
            window.onunload = function(event)
            {
                  if (!g_cancelChange) {
                                   window.event.returnValue=SurveyPopup();
             }
            }                          
        }        
       
     </script>
     
            <script type="text/javascript">
                  var g_cancelChange = false;
                  document.onmouseout = function(event)
                  {
                        g_cancelChange = false;
                  }
                  document.onmousemove = function(event)
                  {
                        g_cancelChange = true;
                  }
                  window.onunload = function(event)
                  {
                        if (!g_cancelChange) {
                     window.event.returnValue=SurveyPopup();
                        }
                  }
            </script>
 
any idea where I am doing mistake.
thanks
0
 

Author Comment

by:ken_rgr
ID: 22876622
Hi Any update for my above problem ???
0
 

Author Comment

by:ken_rgr
ID: 22878511
Hellooo, Anybody there to help me ??????
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22878649
Hi,

Sorry it's been a busy day. At first glance I noticed that you have included my bit of code twice. So my first suggestion is to remove that duplicate block of code from the bottom. Also your HTML comment which is embedded within your JavaScript should be directly within the script tags.

I have also made the changes listed below, and pasted the updated code below. Sorry, I haven't got a lot of time tonight, but hopefully this will give you something to play with :)
   - Replaced all window.event with just event, but made sure that event is available. There were some places where the event was null. Your onbeforeunload event handler was using event and window.event.
   - Moved the g_cancelChange variable so that it is global, even though IE will ignore this variable, FireFox/Gecko still require this to be global.
   - I have changed the way onbeforeunload is being bound to its event handler.
   - Removed duplicate block from bottom of page.
   - Corrected HTML comments within script block.

The following line will assign event to event when it isn't null, otherwise event will become window.event. From that line onwards within the scope of event, there is no need to use window.event at all.
event = event || window.event

I don't use cookies client-side with JavaScript very often, so without refreshing my memory on the subject, I am unable to comment upon that part at this point.

See how you get on with this, let me know if your still having problems regarding the popup business.
	<script language="javascript"><!--
		function getCookie(name)         // Getting cookie name
		{
			var dc = document.cookie;
			var prefix = name + "=";
			var begin = dc.indexOf("; " + prefix);
			if (begin == -1) {
				begin = dc.indexOf(prefix);
				if (begin != 0)
					return null;
			}
			else
				begin += 2;
			var end = document.cookie.indexOf(";", begin);
			if (end == -1)
				end = dc.length;
			return unescape(dc.substring(begin + prefix.length, end));
		}
		var surveyCookie1 = getCookie("SelectSurveyNetASPAdvancedCookie");
		var surveyCookie2 = getCookie("SelectSurveyASPAnonymousUserID");                  
		var surveyCookie3 = getCookie("AOASURVEY");
 
		function SurveyPopup() {
			alert(surveyCookie1);
			alert(surveyCookie2);
			alert(surveyCookie3);
 
			if ((surveyCookie1 == null) && (surveyCookie2 == null) && (surveyCookie3 == null)) {
				Surveywindow = window.open('http://qa.mysite.com/Surveys/TakeSurvey.aspx?SurveyID=n4KH4nm', 'Survey', 'center:yes;dialogWidth:900px;dialogHeight:600px');
			}
		}
 
		// This is for FireFox, but it still must be global.
		var g_cancelChange = false;
 
		// For Internet Explorer
		if (navigator.appName == 'Microsoft Internet Explorer') {
			window.onbeforeunload = function(event) {
				event = event || window.event;
				if (event.clientX > document.body.clientWidth && event.clientY < 0 || event.altKey) {
					event.returnValue = SurveyPopup();
				}
			}
		}
		// For FireFox
		else {
			document.onmouseout = function(event) {
				g_cancelChange = false;
			}
			document.onmousemove = function(event) {
				g_cancelChange = true;
			}
			window.onunload = function(event) {
				event = event || window.event;
				if (!g_cancelChange) {
					event.returnValue = SurveyPopup();
				}
			}
		}
	//--></script>

Open in new window

0
 

Author Comment

by:ken_rgr
ID: 22880113
Hi Thanks for your help.
I think everything seems to be fine as of now. I will know the outcome tommrrow.
If everything is fine by tommorrow I will accept this as solution.
I am really impressed with this forum. Its really worth paying for it.

Thanks Once again.
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22882098
No problem.

I only signed up about a week or two ago and I am also very impressed. I've had 100% success on my questions so far. EE is a fantastic resource.
0
 

Author Comment

by:ken_rgr
ID: 22891902
Hi I am having problem with Fairfox on our QA server.
For one link the pop up is showing up. This link has javascript coding which is doing a post back.
May be because of this its popping up?? I dont know.
Even my coding Survey popup also not working properly on Fairfox.
I am really worried. I couldnt finish this job in time.
In internet Explorer its working perfectly. I dont know why its not working in FF
can you come up with a better solution like event.clientX in FairFox??
Let  me know.
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22892995
According to the following link:
http://developer.mozilla.org/en/docs/DOM:window#Event_Handlers

There is a window.onclose event in FireFox. Thus in FF it should just be a case of:

window.onclose = function(event) {
     showPopup();
};

This event should work in FF, Chrome, and Safari. In IE you will want to continue as you are.
0
 

Author Comment

by:ken_rgr
ID: 22896981

Hey  the above code is not working at all in Fairfox3.



0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22897962
I'm really sorry but I don't know what else to suggest.

As I said previously, if it were me, I would just provide a button at the top of the page which people can click to fill out a survey. I don't know the world-wide statistics, but most of the people I know have a popup blocker enabled; thus they will would not see your survey by default. But providing a button is reliable in the sense that everyone can see and use it.

Alternatively you could show a popup survey when your home page is loaded for the first time. You could use a cookie to determine whether the page is being loaded for the first time.

Or maybe you could have your server-side application generate a client-side script once a predetermined number of post backs have occurred. If the post back counter is equal to, say, 5 then generate a script which will show the popup on the page immediately. This would also prevent the survey from pestering the same person every time they close a window.
0
 

Author Comment

by:ken_rgr
ID: 22898898
Hi I need to create a javascript file for my code as per my requirements.
I copied all my code in a js file and in the script tag src gave the link like mentioned below.
   <script type="text/javascript" language="javascript" src="../Assets/javascripts/surveyscript.js" >
  </script>

But now its not working . Why??  I checked the path everything is correct why is this.
This javascript is killing me.
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22899136
Provided that you've got the path correct, there shouldn't be a problem with that. However, you don't need to use the language attribute because as per the W3C standards, it is deprecated.

<script type="text/javascript" src="../Assets/javascripts/surveyscript.js"></script>

As I am sure you are aware, "../Assets/javascripts/surveyscript.js":

Root
   FolderA
      myPage.html
   Assets
      javascripts
          surveyscript.js

If the assets folder is in the same directory as your page then perhaps you should try:

"Assets/javascripts/surveyscript.js" instead.

Also, make sure that you have the correct access permissions to that file. If you are sure that all of the above should be fine, then perhaps an error is occurring within the script. In FireFox, are any error messages or warnings being shown in the console window?
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22899166
Also, any folder paths in your JavaScript file are NOT relative to the JavaScript file!!

For example, if your JS file includes: window.open('popupPage.html');
And the popup page file is in the javascripts folder, that URL is wrong because the paths are still relative to the active HTML page (in this case myPage.html).

So, you would need: window.open('../Assets/javascripts/popupPage.html');
0
 

Author Comment

by:ken_rgr
ID: 22899393
Nope still not working.
path for the javascript file is corrent.
May be is it because onbeforeunload event ??
And I am not even getting any error also.
0
 
LVL 13

Accepted Solution

by:
numberkruncher earned 500 total points
ID: 22899603
At the very top of your javascript file add this:

alert('Hello World!');

If the message appears when the page first loads, it was loaded correctly; otherwise the script has not been loaded.

If this message does appear, then there is either some sort of syntax error in your script file, or your not referencing your paths correctly within the javascript file. If all fails, post your javascript file as an attachment. You will need to rename the extension to .txt because EE doesn't allow extensions that it does not recognise.
0

Featured Post

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Script Error 5 44
Chromium browser keeps re-appearing 3 49
Install OSX 10.7 or above on iMac with new Hard drive 10 53
Computer Virus 30 72
Let’s list some of the technologies that enable smooth teleworking. 
This guide will walk you through the essential considerations and tech stack for building scalable websites. Know how to grow your business the smart way!
Video by: Tony
This video teaches viewers how to export a project from Adobe Premiere Pro and the various file types involved.
Viewers will learn how to use the Hootsuite Dashboard.

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question