August 24, 2012

Application Shutdown

When you are writing a Smart application, you have to keep in mind that it's not a 'real' application but a web page running in a browser. As such, the user can at any time close the tab with your application or close a browser. The browser may also crash and the whole operating system hosting the browser that runs your application may die unexpectedly.

In short, there are many ways of terminating your application and you cannot be sure that you'll be notified when the application is being closed. You cannot always expect that your application will be given a signal before it is being closed. The best way to run a code on application shutdown is not to do it. [That is, restructure your code so it doesn't have to be run on application shutdown. Execute it before that.]

If you really want to run code on application shutdown, Smart offers you few ways to do it. You can override TForm.FinalizeObject or TApplication.ApplicationClosing. You can also write an event handler for TApplication.OnBeforeUnload and for TApplication.OnUnload, which roughly correspond to Delphi's OnCloseQuery and OnClose events. The only problem is that your application will not run on all major browsers correctly so you'll have to find a workaround for some browsers or just remove support for them.

To test the browser support for executing shutdown code, I have written a small program that logs various times during application startup and shutdown into cookie storage. Next time you start the application times from the previous run will be shown. Following points in the code are logged:

  • TApplication.ApplicationStarting
  • TForm.InitializeObject
  • TForm.FinalizeObject
  • TApplication.ApplicationClosing
  • TApplication.OnBeforeUnload
  • TApplication.OnUnload

As we could expect, the first two points which are executed while application is being started are always logged. Other four (called during the application shutdown) are correctly called only on some browsers.

Following browsers were tested:

  • Chrome 21.0
    Shutdown code is executed on first reload (F5) but not on subsequent ones. Shutdown code is not executed if tab or browser is closed.
  • Firefox 14.0.1
    Shutdown code is always executed.
  • Opera 12.01
    Shutdown code is never executed.
  • Safari 5.1.7 on Windows
    Shutdown code is always executed.
  • Smart 1.0.122 (internal browser)
    Shutdown code is always executed except that OnBeforeUnload is never called.
  • Safari on iOS 5.1
    Shutdown code is always executed except that OnBeforeUnload is never called.

Following two screens show results from Opera (left) and Safari on Windows (right).