Javascript 如何在单击“后退”按钮时警告用户?
Javascript 如何在单击“后退”按钮时警告用户?,javascript,angularjs,Javascript,Angularjs,www.example.com/templates/create template 如果用户离开create template页面,我想警告他们。我的意思是他们是转到另一个页面还是模板 我使用这段代码在页面重新加载和路由更改时警告用户表单是否脏 函数preventPageReload(){ var warningMessage='您所做的更改可能无法保存'; if(ctrl.templateForm.$dirty&&!confirm(警告消息)){ 返回错误 } } $transitions
www.example.com/templates/create template
如果用户离开create template
页面,我想警告他们。我的意思是他们是转到另一个页面还是模板
我使用这段代码在页面重新加载和路由更改时警告用户表单是否脏
函数preventPageReload(){
var warningMessage='您所做的更改可能无法保存';
if(ctrl.templateForm.$dirty&&!confirm(警告消息)){
返回错误
}
}
$transitions.onStart({},preventPageReload);
window.onbeforeunload=preventPageReload
但是,您可以如下使用:(使用$transitions
)
使用$transitions.onBefore
代替$transitions.onStart
希望这能对你有所帮助。我还没有测试解决方案。也可以帮助您。首先,您用错了: 发件人: 及
- funcRef是对函数或函数表达式的引用
- 函数应该为事件对象的returnValue属性指定一个字符串值,并返回相同的字符串
onbeforeunload
中打开任何对话框
因为您不需要在卸载之前使用onbeforeunload
的确认对话框。当您试图离开页面时,如果函数返回的值不是null
或undefined
,浏览器将为您执行此操作
现在,只要您在同一页上,onbeforeunload
就不会触发,因为从技术上讲,您仍然在同一页上。在这种情况下,您将需要一些在状态更改之前激发的函数,您可以将确认对话框放在其中
如何做到这一点取决于您使用的路由器。我在我当前的项目中使用ui路由器,并且我在功能中进行了检查
编辑: 您可以保留
preventPageReload
,以便在角度上更改状态。但当用户输入新地址或试图通过链接等离开页面时,您需要一个不同的功能
例如:
window.onbeforeunload = function(e) {
if (ctrl.templateForm.$dirty) {
// note that most broswer will not display this message, but a builtin one instead
var message = 'You have unsaved changes. Do you really want to leave the site?';
e.returnValue = message;
return message;
}
}
您可能希望查看为此目的而制定的现有指令,比如,或者查看@AlekseySolovey,我已经看到了该指令。不幸的是,我不能使用它,因为它不仅仅是一种形式。它也是一个HTML模板编辑器。此外,它们使用
$rooteScrop
来侦听$locationChangeStart
和$stateChangeStart
。我有,但我仍然有同样的问题。你能用$locationChangeStart
和ui路由器
吗?我知道这一点和所有的转换hoook。它不起作用。啊,让我给你试试。你能不能提供任何我可以正确调试的实时链接。有空吗?好的。你知道当你点击back
按钮时,Codepen是如何显示Leave site?
对话框的吗?就像我说的:onbeforeuload需要返回一些值,而不是null或未定义的值。“离开网站?”是来自chrome的内置消息。他们这样做是为了防止恶意用户对对话框的性质产生误解。您知道如何显示它吗?
Note: To combat unwanted pop-ups, some browsers don't display prompts
created in beforeunload event handlers unless the page has been interacted
with; some don't display them at all. For a list of specific browsers, see the
Browser_compatibility section.
window.onbeforeunload = funcRef
window.onbeforeunload = function(e) {
if (ctrl.templateForm.$dirty) {
// note that most broswer will not display this message, but a builtin one instead
var message = 'You have unsaved changes. Do you really want to leave the site?';
e.returnValue = message;
return message;
}
}