Hi,
I'm no expert in JS but I'd like to suggest something. This might not be the best solution but here it goes...
What you want to do is record the currentTime of the media when user closes the window, right? An AJAX request might not work on beforeunload I guess.
What you can try is....save the curerntTime to the localStorage every second using the setInteval method. The currentTime stays in the localStorage when the user closes the window. But when the user comes back to your site, you can retrieve it from localStorage and store in your database using AJAX.
I'm not sure if that would help