Javascript 如何在onbeforeunload事件中捕获目标url
我想使用onbeforeunload在离开某些页面之前向用户发送消息。 是否有可能知道在onbeforeunload事件中他们应该跳转到哪个url 谢谢 是否有可能知道在onbeforeunload事件中他们应该跳转到哪个urlJavascript 如何在onbeforeunload事件中捕获目标url,javascript,javascript-events,Javascript,Javascript Events,我想使用onbeforeunload在离开某些页面之前向用户发送消息。 是否有可能知道在onbeforeunload事件中他们应该跳转到哪个url 谢谢 是否有可能知道在onbeforeunload事件中他们应该跳转到哪个url 不,绝对不是。onbeforeunload事件仅告诉您页面即将被卸载,而不告诉您卸载原因。这取决于用户如何离开页面。 如果他们在地址栏中键入url,那么你就不走运了。据我所知,没有办法捕获地址栏跳转的url 如果他们正在点击页面某处包含的链接,您可以使用单击事件捕获ur
不,绝对不是。
onbeforeunload
事件仅告诉您页面即将被卸载,而不告诉您卸载原因。这取决于用户如何离开页面。
如果他们在地址栏中键入url,那么你就不走运了。据我所知,没有办法捕获地址栏跳转的url
如果他们正在点击页面某处包含的链接,您可以使用单击事件捕获url,然后决定如何处理
我提出了一个类似的问题因为我有一个项目来修复批发订单。在填写订单的过程中,我客户的客户会返回目录查看产品的详细信息页面,并在他们的订单上公布当前信息。
通过使用下面的代码(使用JQuery,但我相信如果有必要的话,您可以用纯Javascript创建相同的东西),我可以知道用户何时单击一个链接将离开订单表单,然后让他们选择在新窗口/选项卡中打开链接,或者在当前窗口中加载url并丢失表单数据,或者只是回到表格上。这段代码适用于所有主要浏览器,至少是它们的最新版本
$('body a').click(function(e) {
//if link references a page element
if ($(this).attr('href').charAt(0)=="#") {
return;
}
//check if link is to same window
var pathname = window.location.pathname;
var pathname2 = $(this).attr('href');
pathname2 = pathname2.replace(/^.+\.\//, '');
if (pathname.indexOf(pathname2) >= 0) {
//link clicked is contained on same page
//prevent page from getting reloaded & losing data
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
return;
}
//link clicked on is another page
if (hasMerchandise) { //var to indicate user has items on order form
//give user options: leave page, open link in other page, stay, etc.
// $('.popupForm-handleExitRequest').click(); //roll your own code
//prevent page from getting reloaded & losing data
//in case user wants to cancel page change or open link in another window
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
} else {
//load new page
$(this).removeAttr('target');
}
});
可以在当前页面的每个链接上添加
单击事件侦听器。使用它,您至少可以可靠地判断用户点击了哪个传出链接。但是它很难实现,并且不适用于任何其他用户操作(例如,用户单击“后退”按钮)。所有form.submit事件都可以查看表单提交URL。并考虑到所有DOM操作(动态添加元素-您还必须将单击事件附加到它们;jQuerylive
在这方面可能会有所帮助)。