pirsch icon indicating copy to clipboard operation
pirsch copied to clipboard

Track visitors leaving a website

Open Kugelschieber opened this issue 3 years ago • 2 comments

Useful to calculate the time on the page more precisely.

https://css-tricks.com/send-an-http-request-on-page-exit/

Kugelschieber avatar Apr 09 '22 12:04 Kugelschieber

grafik

Kugelschieber avatar May 01 '22 17:05 Kugelschieber

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 avatar May 02 '22 14:05 Kugelschieber

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.

Kugelschieber avatar Aug 19 '23 13:08 Kugelschieber