how to create exit intent popup with custom content

I want to show a custom feedback popup when user tries to close my website tab/browser.

As I am using WordPress for my development. I don’t want to use plugin for it.

I am aware that this question has been asked a million times, but it seems this technology is not possible at the moment as it was in the past. Now that I research on this topic, all the exit intent popup only works when the user moves his pointer away from the document but not when the user closes the window or directs to another page.

In JavaScript, you could achieve the same using the onbeforeunload event but now it isn’t possible to override the default message that popups and use your own modal or alert message in place of it.

Is there any alternate way of it? If not in JavaScript, in another technology maybe? Or is it something that is no longer followed anymore?

I have tried using following code, even multiple codes

$(window).bind("beforeunload",function(event) {
    if(hasChanged) return "My message";
});

But it’s not working as expected.

Need help!