最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Event to be triggered when leaving website or closes the browser - Stack Overflow

programmeradmin0浏览0评论

I´m trying for a while execute a JavaScript function when a user leaves web site by typing a address in the browser and hits return or the user closes the browser clicking in the x button.

I tried the unload event but I cannot get the alert.

This is what I am doing:

$(window).unload(function () {
    alert("Are you sure?");
});

also

$(body).unload(function () {
    alert("Are you sure?");
});

I am running out of ideas!

I´m trying for a while execute a JavaScript function when a user leaves web site by typing a address in the browser and hits return or the user closes the browser clicking in the x button.

I tried the unload event but I cannot get the alert.

This is what I am doing:

$(window).unload(function () {
    alert("Are you sure?");
});

also

$(body).unload(function () {
    alert("Are you sure?");
});

I am running out of ideas!

Share Improve this question edited Nov 2, 2022 at 22:11 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Nov 30, 2012 at 14:39 Guilherme LongoGuilherme Longo 2,3087 gold badges47 silver badges65 bronze badges 2
  • 1 this is what you're looking for – Zathrus Writer Commented Nov 30, 2012 at 14:41
  • possible duplicate of jQuery - beforeunload – Ram Commented Nov 30, 2012 at 14:46
Add a ment  | 

4 Answers 4

Reset to default 2

You can listen to beforeunload event that fires before the unload event, when the page is unloaded.

$(window).on('beforeunload', function(){
    // ...
})

Some browsers (like Chrome) block alerts in unload event handlers, to prevent exactly these kind of annoying messages. Try a console.log or put a breakpoint in to find out if the handler is triggered when you don't have an alert there.

SO question on a similar line:

window.onunload is not working properly in Chrome browser. Can any one help me?

You can only pass the alert by returning a string in a beforeunload handler (HT @undefined), but I would avoid even that, because popups are generally bad, and most people will do minimum processing to work out the make-this-thing-go-away option before they actually think about the contents of the box.

The function you defined in window.onbeforeunload if it returns a string it will pop up a confirm navigation prompt with that message.

Alerts may be ignored!

window.onbeforeunload = function() {
    return "All unsaved data will be lost. Are you sure?";
};

Some browsers handle the onbeforeunload differently. Recent Firefox for example will ignore your return string and just display a standard message.

$(window).bind('beforeunload', function(){
    alert("Are your sure?")
});
发布评论

评论列表(0)

  1. 暂无评论