简体   繁体   中英

Trying to execute javascript on window.onbeforeunload

I am not very strong in javascript, but what I am trying to do is pretty easy and I am almost there, but I just don't how to complete the task. I have some javascript that I deployed off of a website, called "Feebackify" ... it prompt the user with a form to provide feedback on their visit. it works great, but to make it work I the user has to press a button or a link... I don't want this, I want the javascript to execute when they try to leave the page ... either going to another page of the site or exiting. I tried using the following code:

 <script type="text/javascript">
     window.onbeforeunload = function () {

         FBY.showForm(4530); 

     }
 </script> 

here is the original script:

<script type="text/javascript">
    var fby = fby || [];
    //fby.push(['showTab', { id: '4530', position: 'right', color: '#FF1F3A'}]);
    (function () {
        var f = document.createElement('script'); f.type = 'text/javascript'; f.async = true;
        f.src = '//cdn.feedbackify.com/f.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(f, s);

    })();  
</script>

my code does "something" well it at least flashes a form when I expect it to, but it does not execute he script... can someone give me some pointers. Thank you

You can do something like this. You might want to take a look at window.onbeforeunload to be sure you fully understand the event.

Summary

An event that fires when a window is about to unload its resources. The document is still visible and the event is still cancelable.

function sure(evt) {
    var div = document.createElement("div");

    div.textContent = "Do things before checking the user want to leave, dynamically load your form";
    document.body.appendChild(div);

    // The question that will the user will be asked
    return "Leave page?";
}

window.addEventListener("beforeunload", sure, false);

on jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM