Skip to content

Instantly share code, notes, and snippets.

@iDanielLaw
Forked from biswajitpaul01/example.html
Created October 22, 2020 07:24
Show Gist options
  • Save iDanielLaw/fff87b819f0b34dbe12026067ff7f294 to your computer and use it in GitHub Desktop.
Save iDanielLaw/fff87b819f0b34dbe12026067ff7f294 to your computer and use it in GitHub Desktop.
navigator.sendBeacon example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Send Bacon Example</title>
</head>
<body>
<button type="button" id="button">Send Response</button>
<script>
const url = "/print-ajax.php";
button.addEventListener("click", () => {
let formData = new FormData();
formData.append("name", "john does" );
if (navigator.sendBeacon) {
formData.append("from", "sendBeacon");
navigator.sendBeacon(url, formData);
} else {
formData.append("from", "fetch");
fetch(url, {
type: "post",
body: formData
});
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment