Solved

captureing browser close (x) button click in Fairfox3

Posted on 2008-11-02
33
2,103 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
  • 17
  • 16
33 Comments
 
LVL 13

Expert Comment

by:numberkruncher
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:ken_rgr
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Any solution ???
0
 
LVL 13

Expert Comment

by:numberkruncher
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:ken_rgr
Comment Utility
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
Comment Utility
Unfortunately, it's the exact same problem.

Sorry :(
0
 

Author Comment

by:ken_rgr
Comment Utility
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
Comment Utility
Hi Any update for my above problem ???
0
 

Author Comment

by:ken_rgr
Comment Utility
Hellooo, Anybody there to help me ??????
0
 
LVL 13

Expert Comment

by:numberkruncher
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility

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



0
 
LVL 13

Expert Comment

by:numberkruncher
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

Join & Write a Comment

Suggested Solutions

Today companies are subjected to more-and-more data, and it won't stop any time soon.  But there are obvious opportunities for reducing data, particularly data duplicated among companies.
In this article, you will read about the trends across the human resources departments for the upcoming year. Some of them include improving employee experience, adopting new technologies, using HR software to its full extent, and integrating artifi…
The viewer will learn how to create multiple layers to apply various filters and how to delete areas from each layer’s filter.
The viewer will learn how to successfully download and install the SARDU utility on Windows 7, without downloading adware.

763 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now