You could use a combination of Javascript and Flash to achieve what you're looking for.
Use Javascript to detect when the user navigates away from the page. Use the javascript event to call into your Flash movie using ExternalInterface. Once your code is called, you can handle the event as needed.