无法阻止浏览器页面在角度应用程序中刷新/重新加载 [英] Can not prevent browser page refresh/reload in angular application
问题描述
我的网站带有angularjs SPA.当用户单击刷新按钮或按F5/Ctrl + F5时,我要阻止或中止页面重新加载.不幸的是,具有onbeforeunload
和onunload
事件的解决方案不起作用.实际上,它们被称为,到达event.preventDefault()
行,控制台中有任何消息,但浏览器继续加载页面.
I have my site with angularjs SPA. When user clicks on refresh button or press F5/ Ctrl + F5 to I want to prevent, or abort page reloading. Unfortunately, solution with onbeforeunload
and onunload
events are not working. Actually, they are called, event.preventDefault()
line is reached, there are any messages in console, but browser continue to load page.
我当前的模块.run()
代码:
let window = angular.element($window);
window.on("beforeunload", (event) => {
event.preventDefault();
}).on("unload", (event) => {
event.preventDefault();
});
// This is just for sure that I have my handlers registered
$window.onbeforeunload = (event) => {
event.preventDefault();
}
$window.onunload = (event) => {
event.preventDefault();
}
我该如何真正解决这个问题?
How can I really handle this in angular?
更新
我需要这个来重新加载实际状态,而不是页面.因此,当用户单击刷新时,我只想用$stateProvider
重新加载当前状态,而不是重新加载整个页面
I need this for reloading actual state instead of page. So when user clicks refresh I want to just reload current state with $stateProvider
and not to reload the whole page
推荐答案
Check out what Mozilla has to say about unload events. It looks like it is not possible to prevent a refresh like you want to. The only think that you can do is to ask the user if he/she really wants to leave the page.
我想您可以在用户回答他/她不想离开当前页面的情况下重新加载当前状态.
I guess you could reload the current state in the case the user answers that he/she does not want to leave the current page.
window.onbeforeunload = function(event) {
// do some stuff here, like reloading your current state
//this would work only if the user chooses not to leave the page
return 'why would you do that???';
}
我为您创建了小提琴.
这篇关于无法阻止浏览器页面在角度应用程序中刷新/重新加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!