Use beacon (#19)
Perfect. Tried with send beacon before. Dodn work for me. Because was using get instead o post.
This commit is contained in:
21
via.go
21
via.go
@@ -11,6 +11,7 @@ import (
|
|||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -146,8 +147,11 @@ func (v *V) Page(route string, initContextFn func(c *Context)) {
|
|||||||
}
|
}
|
||||||
headElements := v.documentHeadIncludes
|
headElements := v.documentHeadIncludes
|
||||||
headElements = append(headElements, h.Meta(h.Data("signals", fmt.Sprintf("{'via-ctx':'%s'}", id))))
|
headElements = append(headElements, h.Meta(h.Data("signals", fmt.Sprintf("{'via-ctx':'%s'}", id))))
|
||||||
headElements = append(headElements, h.Meta(h.Data("init", `window.addEventListener('beforeunload', (evt) => {
|
unloadJS := fmt.Sprintf(`
|
||||||
evt.preventDefault(); evt.returnValue = ''; @get('/_session/close'); return ''; })`)))
|
window.addEventListener('beforeunload', (evt) => {
|
||||||
|
navigator.sendBeacon('/_session/close', '%s');
|
||||||
|
});`, c.id)
|
||||||
|
headElements = append(headElements, h.Meta(h.Data("init", unloadJS)))
|
||||||
headElements = append(headElements, h.Meta(h.Data("init", "@get('/_sse')")))
|
headElements = append(headElements, h.Meta(h.Data("init", "@get('/_sse')")))
|
||||||
bottomBodyElements := []h.H{c.view()}
|
bottomBodyElements := []h.H{c.view()}
|
||||||
bottomBodyElements = append(bottomBodyElements, v.documentFootIncludes...)
|
bottomBodyElements = append(bottomBodyElements, v.documentFootIncludes...)
|
||||||
@@ -394,10 +398,15 @@ func New() *V {
|
|||||||
actionFn()
|
actionFn()
|
||||||
})
|
})
|
||||||
|
|
||||||
v.mux.HandleFunc("GET /_session/close", func(w http.ResponseWriter, r *http.Request) {
|
v.mux.HandleFunc("POST /_session/close", func(w http.ResponseWriter, r *http.Request) {
|
||||||
var sigs map[string]any
|
body, err := io.ReadAll(r.Body)
|
||||||
_ = datastar.ReadSignals(r, &sigs)
|
if err != nil {
|
||||||
cID, _ := sigs["via-ctx"].(string)
|
log.Printf("Error reading body: %v", err)
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
cID := string(body)
|
||||||
c, err := v.getCtx(cID)
|
c, err := v.getCtx(cID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
v.logErr(c, "failed to handle session close: %v", err)
|
v.logErr(c, "failed to handle session close: %v", err)
|
||||||
|
|||||||
Reference in New Issue
Block a user