【问题标题】:How can I warn user on back button click?如何在单击后退按钮时警告用户?
【发布时间】:2018-12-21 18:09:58
【问题描述】:

www.example.com/templates/create-template

如果用户离开create-template 页面,我想警告他们。我的意思是他们是去另一个页面还是去templates


如果表单变脏,我使用此代码警告用户重新加载页面和路由更改。

function preventPageReload() {
  var warningMessage = 'Changes you made may not be saved';
  if (ctrl.templateForm.$dirty && !confirm(warningMessage)) {
    return false
  }
}

$transitions.onStart({}, preventPageReload);
window.onbeforeunload = preventPageReload

如果通过单击菜单或手动更改它来完成页面重新加载和路由更改,它会按预期工作。但是,当我单击后退按钮时,它不会触发警告。只有当我第二次单击后退按钮、重新加载页面或手动更改路线时才会这样做。

我正在使用 ui-router。当您单击back 按钮时,您会从app.templates.create-template 状态转到app.templates 状态。

如果他们按下返回按钮如何警告?

【问题讨论】:

  • 您可能想查看为此目的制定的现有指令,例如angular-unsavedChanges,或查看their implementation
  • @AlekseySolovey 我看过那个指令。不幸的是我不能使用它,因为它不仅仅是一种形式。它也是一个 HTML 模板编辑器。此外,他们使用$rooteScrop 来监听$locationChangeStart$stateChangeStart。我有,但我仍然有同样的问题。

标签: javascript angularjs


【解决方案1】:

但是,您可以像下面这样使用它:(使用$transitions

$transitions.onBefore({}, function(transition) {
    return confirm("Are you sure you want to leave this page?");
});

使用$transitions.onBefore 而不是$transitions.onStart

希望这对您有所帮助。我还没有测试解决方案。 This one也可以帮到你。

【讨论】:

  • 你可以使用$locationChangeStartui-router 吗?
  • 我知道这一点以及所有的过渡钩子。它不起作用。
  • 啊,让我为你试一试。您能否提供任何我可以正确调试的实时链接。有 Jsfiddle 吗?
【解决方案2】:

首先,你用错了:

来自https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

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
  • funcRef 是对函数或函数表达式的引用。
  • 该函数应为 Event 对象的 returnValue 属性分配一个字符串值并返回相同的字符串。

您无法在onbeforeunload 中打开任何对话框。

因为您不需要与onbeforeunload 的确认对话框。如果在您尝试离开页面时函数返回的值不是nullundefined,浏览器将为您执行此操作。

现在,只要您在同一页面上,onbeforeunload 就不会触发,因为从技术上讲,您仍然在同一页面上。在这种情况下,您将需要一些在状态更改之前触发的函数,您可以在其中放置确认对话框。

具体操作方式取决于您使用的路由器。我在当前项目中使用 ui-router,并且在 uiCanExit 函数中进行了检查。


编辑

您可以保留您的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;  
  }
}

【讨论】:

  • 好的。你知道点击back按钮时Codepen如何显示Leave site?对话框吗?。
  • 就像我说的:onbeforeunload 需要返回一些值,而不是 null 或 undefined。 “离开站点?”是来自 chrome 的内置消息。他们这样做是为了防止恶意软件在对话性质方面误导用户。
  • 你知道怎么显示吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
相关资源
最近更新 更多