-2

No, I'm not trying to make an annoying popup. I have a simple webpage that is a web-based control for a SOA tool that will allow our clients mobile access to systems we put in their locations. If the user closes the webpage without using a "Disconnect" button that closes the communication tunnel on the service side before closing the window itself, the system remains active until the service times out. That may not sound terrible, but the same communication tunnel is used by in-house staff in high-priority situations, and if they cannot access it because the customer's web service is tying it up, that is a Very Bad Thing.

So, I want to prevent the user navigating away from the page or closing the tab or browser instance by any other means than clicking "Disconnect". I'm sure it's possible, I just need a nudge in the right direction. The solution must be as browser-agnostic as possible, especially concerning mobile browsers.

KeithS
  • 70,210
  • 21
  • 112
  • 164
  • Why not use some kind of ping from the client to the server - if the server doesnt receive a ping within x seconds from the client the session is automatically closed from the sever - trying to do this kind of thing on the client is going to open a huge can of worms – Manse Nov 07 '11 at 19:39
  • That's certainly an option. We are investigating something like window.onbeforeunload because that would require the least bandwidth, which is important for mobile users. Requiring the client to ping a method on the service would first require maintaining a mobile internet connection, and then the user would be making a service call every x seconds (probably 10 or so), slowly eating bandwidth. However, the "keepalive" quality is useful in other ways (the hardware behind this SOA requires a similar keepalive; it just has a MUCH longer timeout than even the WCF service), so this may work well. – KeithS Nov 07 '11 at 19:44
  • This might be a duplicate of this question: http://stackoverflow.com/questions/821011/how-do-you-prevent-javascript-page-from-navigating-away – Anderson Green Mar 19 '13 at 02:34

2 Answers2

1

You can try using the onbeforeunload handler. but it is not always thrown.

See fiddle using jQuery: http://jsfiddle.net/maniator/qpK7Y/
See fiddle with pure javascript: http://jsfiddle.net/maniator/qpK7Y/10/

Naftali
  • 144,921
  • 39
  • 244
  • 303
0

You can't stop the using from closing the window via the close button at the top right. You can force a child window to retain focus like this though:

Declare a global variable:

var childWindow;

Assign the variable to a window object

childWindow = window.open("...", "...");
if (childWindow){
    childWindow.focus();
}

To force focus on the child window, use the onfocus event on the parent:

focusChildWindow = function(){
    if (childWindow != null){
        childWindow.focus();
    }
}

<body onfocus="focusChildWindow();" ...>
James Johnson
  • 45,496
  • 8
  • 73
  • 110