卸载页面时上报日志

当刷新页面或关闭页面时,上报日志

function report() {
	let myHeaders = new Headers();
	myHeaders.append("Accept", "application/json");
	myHeaders.append("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMTI3LjAuMC4xOjgwMDAvYXBpL2FkbWluL2F1dGgiLCJpYXQiOjE2ODY3ODc3NTEsImV4cCI6MTY4NjgxNjU1MSwibmJmIjoxNjg2Nzg3NzUxLCJqdGkiOiJJSXpkZGhHbEEwMllHcEE4Iiwic3ViIjoiNjYzM2ZlNTUtYmZmYi0zY2U0LWI1NTItNjYyNWE5MzlkN2EzIiwicHJ2IjoiN2ViYjhhMmNjMWQ5NWI2MmM5NTk0YTIyYzljZWMyMmYzOGRiNWQzMSJ9.f5PhRge-p2m6kDKjp-rSfTUFa54uNgY3v9DnbmS_XOE");

	let formData = new FormData();
	formData.append("a", "aa");
	formData.append("b", "bb");
	formData.append("c", "cc");

	let requestOptions = {
		method: "POST",
		headers: myHeaders,
		body: formData,
		redirect: "follow",
		mode: "cors",
		cache: "no-store",
		keepalive: true,
	};

	fetch('http://localhost/test/report.php', requestOptions)
		.then(response => {
			console.log(response.ok);
		})
		.catch(error => {
			console.error(error);
		});
}

window.addEventListener("beforeunload", report);

关键点:

  • 使用 Fetch Api
  • 配置 mode: "cors"
  • 配置 keepalive: true
posted @ 2023-08-17 10:05  Tiac  阅读(9)  评论(0编辑  收藏  举报