What you did is correct apart from the event name and the fact that alert will be blocked in that particular event.
You can show a message like this:
window.addEventListener("beforeunload", (ev) =>
{
ev.preventDefault();
return ev.returnValue="Are you sure you want to close?";
});
Hope this helps.