There’s out there some free and paid solutions to show a popup/modal when a user tries to leave your page, but since I’m all about DIY, i coded my own. And of course, I will also share the code. It’s not really special, it’s just a simple script with jQuery and CSS3.
See the Pen PopUp/Modal on Leave by Pedro Lopes (@ORiOn16) on CodePen.