pirsch-analytics / pirsch

Pirsch is a drop-in, server-side, no-cookie, and privacy-focused analytics solution for Go.
https://pirsch.io
GNU Affero General Public License v3.0
928 stars 43 forks source link

Track visitors leaving a website #256

Closed Kugelschieber closed 1 year ago

Kugelschieber commented 2 years ago

Useful to calculate the session duration more precisely. This would be a separate request only updating the session duration.

Kugelschieber commented 2 years ago

grafik

Kugelschieber commented 2 years ago

Demo

static/
  page.html
  index.html
main.go
package main

import (
    "io"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/hit", func(w http.ResponseWriter, r *http.Request) {
        body, err := io.ReadAll(r.Body)

        if err != nil {
            log.Printf("Error reading body: %v", err)
        }

        log.Println(string(body))
    })
    http.Handle("/", http.FileServer(http.Dir("static")))
    http.ListenAndServe(":8080", nil)
}

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <a href="/page.html">Page</a>

    <script type="text/javascript">
        document.addEventListener("visibilitychange", () => {
            if(document.visibilityState === "hidden") {
                navigator.sendBeacon("/hit", JSON.stringify({
                    page: "home"
                }));
            }
        });
    </script>
</body>
</html>

page.html

<!DOCTYPE html>
<html>
<head>
    <title>Page</title>
</head>
<body>
    <a href="/">Home</a>

    <script type="text/javascript">
        document.addEventListener("visibilitychange", () => {
            if(document.visibilityState === "hidden") {
                navigator.sendBeacon("/hit", JSON.stringify({
                    page: "page"
                }));
            }
        });
    </script>
</body>
</html>
Kugelschieber commented 1 year ago

This interferes with sessions and might artificially increase the time on the website, as tabs are often never closed or after a very long time.