关闭页面前执行JS函数|重新导向 [英] Execute JS function just before page close | redirect

查看:99
本文介绍了关闭页面前执行JS函数|重新导向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET Web表单,c#.

I am using ASP.NET web forms, c#.

我需要在页面关闭之前执行JS函数-它以任何关闭方式-作为重定向或任何其他方法.

I need to execute a JS function just before the page closes - any which way it closes - being a redirect or any other method.

其他信息:

作为一些额外的信息;该功能将是HTTP POST到另一个页面,我需要一些服务器端代码来执行.

As some extra info; the function will be an HTTP POST to a different page, I need some server side code to execute.

请牢记此信息-一种使我在页面关闭时执行服务器端代码的解决方案同样适用于我.

With this info in mind - a solution allowing me to execute server-side code when a page closes will work for me as well.

推荐答案

看看JavaScript函数 window.onbeforeunload .

Have a look at the JavaScript function window.onbeforeunload.

本质上,浏览器在检测到页面关闭时会触发此事件,并允许您通过从此函数返回字符串来自定义消息.

Essentially, browsers fire this event when they detect that the page is closing, and allow you to customize a message by returning a string from this function.

但是,您无法控制用户是否要过早或意外地强制关闭页面.

You cannot however, control if the user wants to force close the page early, or unexpectedly.

window.onbeforeunload = function(e) {
    // do some ajax post here
    // 

    // Display a message (or generic message in some browsers) and allow the user to cancel leaving the page.
    return 'Dialog text here.';
};

请注意,此解决方案尝试警告用户,并允许取消卸载.这可能对您来说并不理想,但应该可以.

Note that this solution tries to warn the user and allows the unload to be cancelled. This might not be ideal for you, but should work.

https://developer.mozilla.org/zh-US/docs/Web/API/WindowEventHandlers/onbeforeunload

这篇关于关闭页面前执行JS函数|重新导向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆