Javascript alert message on browser close and redirect

Hello WPMU.

I have a client who would like on her sales pages that when a user wants to close her web page that a message would appear saying

"Wait! Have you claimed Your FREE CD Yet?"

And then if the visitor chooses something like "Stay on This Page" then the user would be redirected to the url which has the free cd offer.

I've had some hours of searching and stackoverflow reading and have the following...

var hook = true;
      window.onbeforeunload = function() {
        if (hook) {
          return "Wait! Have you claimed Your FREE CD Yet?"
      function unhook() {

Everything from there works fine, but the redirect url is what I can not find how to work so far anywhere on the internet with a solid explanation of how to do this.

Also, I was wondering if this feature is included in OptimizePress? That is pretty much the only place I recall seeing this implemented.

How can I achieve this?

Best regards WPMU!

  • Ash
    • WordPress Hacker

    Hello @Noahj

    I hope you are well today and thanks for asking the question.

    As far as I know, you can't control this behavior perfectly. As it depends on browser functionality. You can try the following code:

    <script type="text/javascript">
    window.onbeforeunload = function(){ myUnloadEvent(); }
    function myUnloadEvent() {
        var x = confirm('Wait! Have you claimed Your FREE CD Yet??');
        if(x) {'','_blank')
        else {

    Also, it should work with OptimizePress as long you have this in your head section.

    Please let me know.


  • Noahj Champion
    • Site Builder, Child of Zeus

    Hello Ash!

    I tried the code above and then I'm back to not even getting the browser alert message. Is there anything missing from the code perhaps?

    I also attached a screenshot of my theme admin for this funtion that I did have working half way.

    My theme is set up that I don't need to specify the script tags. I don't know javascript until I read it functioning. Like your code for example, I understand what the script is saying.

    I hope the screenshot or just being back to square one with my update may help.

    Thanks again!

  • Ash
    • WordPress Hacker

    Hi there

    Would you please share a link us after enabling the above script? And also please check source code if the script is inserted in the code. Also check check for javascript error in the browser console. To check error in console, just right click on browser, then inspect element and click on console tab.

    Would it be possible for you to insert the code directly in the head tag?


Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.