Created
October 28, 2020 09:18
-
-
Save codebubb/547754a955137c73b92b6cb0d1eba84a to your computer and use it in GitHub Desktop.
Beacon and PageVisibility API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Beacon API</title> | |
| </head> | |
| <body> | |
| <script> | |
| window.events = []; | |
| document.addEventListener('visibilitychange', () => { | |
| if (document.visibilityState === 'visible') { | |
| window.events = []; | |
| window.events.push({ type: 'Session Start', time: Date.now() }); | |
| } | |
| if (document.visibilityState === 'hidden') { | |
| if (window.navigator.sendBeacon) { | |
| window.events.push({ type: 'Session End', time: Date.now() }) | |
| window.navigator.sendBeacon('/log', JSON.stringify(events)); | |
| } | |
| } | |
| }); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment