在页面更改之前运行的 Javascript 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11177233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:47:41  来源:igfitidea点击:

Javascript event that runs before page changes

javascriptjquery

提问by Alex

Is there such a thing?

有这样的事情吗?

I know that I can hook my function on the click event of all links, but there are other situations where a page is changed, like refresh or when a different script changes the window.location

我知道我可以将我的函数挂接到所有链接的点击事件上,但是还有其他情况会更改页面,例如刷新或不同的脚本更改 window.location 时



In the end, I did it by sending a string trough postMessage from the unload event, like this:

最后,我通过从 unload 事件中通过 postMessage 发送一个字符串来做到这一点,如下所示:

$(window).bind('unload', function(e){
  window.parent.postMessage('unloading');
});

in the parent document:

在父文档中:

$(window).bind('message', function(e){     
  if(e.originalEvent.data == 'unloading'){
    // ajax stuff here
  }
});

It appears to work. I probably should have mentioned that there's a iframe involved :)

它似乎有效。我可能应该提到涉及 iframe :)

回答by T.J. Crowder

There's the beforeunloadevent, which is fired when the page is being torn down (either to follow a link, or if the window is being closed, or refresh, etc.). Example:

有一个beforeunloadevent,它在页面被拆除时被触发(或者跟随一个链接,或者如果窗口正在关闭,或者刷新等)。例子:

window.onbeforeunload = function(event) {
    var s = "You have unsaved changes. Really leave?";

    event = event || window.event;
    if (event) {
        // This is for IE
        event.returnValue = s;
    }

    // This is for all other browsers
    return s;
}

There are, for obvious reasons, very strict limits on what you can do in the handler of the beforeunloadevent, and as you can see above beforeunloadhandlers have a different signature than normal event handlers. Basically, your code can't do anything asynchronous, can't open new windows, and can't cancel the event. It canreturn a string, and if it does, the browser will pop up a window asking whether you really want to leave the page, and including your string in that pop-up.

出于显而易见的原因,您可以在beforeunload事件处理程序中执行的操作有非常严格的限制,并且正如您在上面看到的那样,beforeunload处理程序具有与普通事件处理程序不同的签名。基本上,您的代码不能执行任何异步操作,不能打开新窗口,也不能取消事件。它可以返回一个字符串,如果返回,浏览器将弹出一个窗口,询问您是否真的要离开该页面,并在该弹出窗口中包含您的字符串。

From your comment on the question:

从你对这个问题的评论:

I need it before so I can fire a ajax request and update some things...

我之前需要它,所以我可以触发一个ajax请求并更新一些东西......

When the page is being torn down, you can usually get away with a synchronousajax call (async: false) provided it doesn't take too long. This is not a great idea and I would strongly recommend avoiding it if you can (for instance, with interim saves), as amongst other things it introduces a delay closing the page. But if you make the call synchronous (as opposed to the default, and greatly preferred, asynchronous call), usually the browser will let you do that. Of course, it does you no good if the browser abruptly terminates (crashes, is force-closed by the user, etc.).

当页面被拆除时,您通常可以通过同步ajax 调用 ( async: false)逃脱,前提是它不会花费太长时间。这不是一个好主意,如果可以(例如,使用临时保存),我强烈建议避免它,因为它会导致关闭页面的延迟。但是如果你使调用同步(而不是默认的,并且非常受欢迎的异步调用),通常浏览器会让你这样做。当然,如果浏览器突然终止(崩溃、被用户强制关闭等)对您没有好处。

Note that the asyncflag is being deprecated and removedfrom jQuery (ticket). I think they plan to deprecate it in 1.8 and actually remove it in 1.9, but it's not hyper-clear from the blog post and ticket.

请注意,该async标志已被弃用并从 jQuery ( ticket) 中删除。我认为他们计划在 1.8 中弃用它并在 1.9 中实际删除它,但从博客文章和票证中并没有非常清楚。

回答by Zbigniew

jQuery has unloadfunction:

jQuery 有卸载功能:

The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

当用户离开页面时, unload 事件被发送到 window 元素。这可能意味着许多事情之一。用户可以点击链接离开页面,或者在地址栏中输入新的 URL。前进和后退按钮将触发事件。关闭浏览器窗口将导致事件被触发。即使页面重新加载也会首先创建一个卸载事件。

Note that this should be binded to windowobject instead of document:

请注意,这应该绑定到windowobject 而不是document

$(window).unload(function() {
    // do something
});

You can also bind handler to beforeunloadevent:

您还可以将处理程序绑定到beforeunload事件:

$(window).bind('beforeunload', function() {
    // do something, preferably ajax request etc
    return 'are you sure?';
});

回答by Pointy

When a page is reloaded, whatever was there before will be gone. Thus, it seems like what you're talking about is something you'd do at DOMReady or "load" in the newpage, since you can't "push" code from the former page into the new context.

当页面重新加载时,之前存在的任何内容都将消失。因此,您所谈论的似乎是您在 DOMReady 或“加载”页面中所做的事情,因为您无法将代码从前一个页面“推送”到新上下文中。