Before I give you any code, I want to be very clear that exit popups are frowned upon in pretty much every development community. They’re annoying to users, create a bad customer experience, and will tick off just about any developer who ever looks at your site.
I can’t say this any more emphatically, but please, please, please do not use exit popups on your site.
OK, now that you’ve ignored that recommendation … here’s how you’d do it anyway.
Your plugin will consist of two files: plugin.php
and plugin.js
in this example (please use unique names).
In addition to the standard plugin headers, your plugin.php
file must contain code to enqueue your script file:
add_action( 'wp_enqueue_scripts', 'wpa_54303_enqueue_scripts' );
function wpa_54303_enqueue_scripts() {
wp_enqueue_script(
'wpa_54303_script', // Unique script name
plugins_url( '/plugin.js', __FILE__ ) // Location of your script file
);
}
This code will load your script on every post and page in the header of your site. Now, just place the relevant code from that tutorial you linked to in your plugin.js
file:
var popit = true;
window.onbeforeunload = function() {
if(popit == true) {
popit = false;
return "Are you sure you want to leave?";
}
}
Let me say one more time that I absolutely do not encourage you use this kind of feature in any site. It’s a quick way to get your name on the top of many developers’ “I don’t like this guy” lists.