简体   繁体   English

尝试在window.onbeforeunload上执行javascript

[英]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. 我的Java语言不是很强,但是我想做的事情很容易,而且我快到了,但是我只是不怎么完成任务。 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. 我从网站上部署了一些JavaScript,称为“ Feebackify”……它会提示用户使用表单来提供有关其访问的反馈。 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. 它很好用,但是要使其正常运行,用户必须按下按钮或链接...我不希望这样,我希望当他们尝试离开页面时执行javascript ...要么转到另一个网站页面或正在退出。 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. 您可能需要查看window.onbeforeunload以确保您完全了解该事件。

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 jsfiddle上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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