This is immoral, and if you were my son and I caught you trying to do that kind of thing on a website you would be out of my will.
Anyway ... you mentioned in a comment in the other answer a particular site. What the site does is not to open a popup, but rather a modal . This is different from opening a popup because it does not interfere with browser behavior and does not open a new tab.
This site uses a library called Ouibounce , which you can find on Github . What the library code does is a function that checks the Y coordinate of the mouse cursor (which for Javascript is relative to the window). If the mouse is less than a number of pixels at the top of the window, it should open a modal.
Note that this means that the modal opens if you move the mouse to any higher point in the browser, such as other tabs or even a menu. It will not necessarily fire only when someone moves the mouse to close or change the tab, nor will it open the modal if the user uses keyboard shortcuts. It will also not work on mobile browsers or use different user experiences for obvious reasons.
If you have no soul or ethics you can modify the Ouibounce code to open a popup instead of a modal.