Files
Mike Dalessio c78bb652d5 Clean up beacon on-visibility-change handling
The previous version was not posting the beacon when the page was
loaded and visible.
2025-08-09 14:09:34 -04:00

24 lines
584 B
JavaScript

import { post } from "@rails/request.js"
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static values = { url: String }
connect() {
this.#sendBeacon()
this.onVisibilityChange = this.#sendBeacon.bind(this);
document.addEventListener("visibilitychange", this.onVisibilityChange)
}
disconnect() {
this.#sendBeacon()
document.removeEventListener("visibilitychange", this.onVisibilityChange)
}
#sendBeacon() {
if (!document.hidden) {
post(this.urlValue, { responseKind: "turbo-stream" })
}
}
}