简体   繁体   English

jQuery中的多个beforeunload处理程序

[英]Multiple beforeunload handlers in jQuery

I am writing JavaScript for a plugin that will be used on clients' sites, and need to use a beforeunload handler to store some information to the user's cookies or localstorage for tracking purposes. 我正在为将在客户网站上使用的插件编写JavaScript,并且需要使用beforeunload处理程序将一些信息存储到用户的cookie或localstorage中以进行跟踪。

However, since I don't control the clients' sites, I'm concerned about the scenario where the client's page has already defined a beforeunload handler before we set ours. 但是,由于我不控制客户端的站点,因此我担心在设置客户端页面之前客户端页面已经定义了beforeunload处理程序的情况。 In particular, I'm worried about the case where the client's JavaScript creates a 'beforeunload' handler that returns a string to create an 'Are you sure you want to leave this page?' 特别是,我担心客户端的JavaScript创建一个“ beforeunload”处理程序,该处理程序返回一个字符串以创建'Are you sure you want to leave this page?' -style popup, and the possibility that adding our handler after that may destroy or otherwise interfere with this functionality. 样式的弹出窗口,以及在此之后添加我们的处理程序的可能性可能会破坏或以其他方式干扰此功能。

Based upon a little experimentation in the console in Chromium, it seems that if I add handlers using jQuery(window).on('beforeunload', handler) , then all the handlers get executed in the order they were added and then the existence and content of any confirmation dialog is determined solely by the final non- undefined return value . 基于Chromium控制台中的一些实验, 似乎如果我使用jQuery(window).on('beforeunload', handler)添加处理jQuery(window).on('beforeunload', handler) ,则所有处理程序都将按照它们添加的顺序执行,然后存在并确认对话框的内容仅由最终的undefined返回值确定 So if the last handler added with an explicit return returns null , no message is shown, and if it returns a string, then a confirmation dialog with that string as its content is shown. 因此,如果最后一个添加显式return的处理程序返回null ,则不会显示任何消息,并且如果返回字符串,则将显示以该字符串为内容的确认对话框。 This is the behaviour I want; 这是我想要的行为; it means that as long as I return undefined from the beforeunload handler that I add, I shouldn't break any of our clients' code. 这意味着,只要我回到undefinedbeforeunload处理程序, 我想补充,我应该不会打破任何的客户的代码。

Can I rely upon this behaviour across all browsers, though? 我是否可以在所有浏览器中都依赖此行为? How about if the client added their original beforeunload handler via a mechanism other than jQuery, like explicitly assigning to window.onbeforeunload or using window.addEventListener ? 客户端是否通过jQuery以外的机制(例如,显式分配给window.onbeforeunload或使用window.addEventListener添加了原始的beforeunload处理程序? How is jQuery handling the assignment of multiple handlers behind the scenes? jQuery如何在后台处理多个处理程序的分配?

what if you do it like this 如果你这样做就怎么办

 var x = window.onbeforeunload
 window.onbeforeunload = function() { 
       // do your stuf
       if (x) return x();
 }

so this way you'll return whatever the initial event handler was suppose to return. 这样一来,您将返回最初假定要返回的事件处理程序。

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

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