The above snippet will have to be added in your master page's html.
You can have a button for the "logout" case.
Unfortunately, there is no reliable way to be notified if the user closes their browser. Other than client-side page unload, which you've said you don't want, about the only other option is periodic Ajax-based polling; both are ugly and notoriously unreliable.
In general, server-side timeouts are a better approach.