Zik*_*iko 2 onbeforeunload aurelia
众所周知,当我们点击浏览器上的刷新按钮时,我们可以弹出一个询问我们是否确定刷新页面的弹出窗口。通常它是通过在 onbeforeunload 上添加一个事件监听器来完成的。
但是,在我的 Aurelia 应用程序中,我尝试这样做,但它不起作用。
假设这是我的 app.js(根 ModelView)
export class App {
this.refreshClicked = () =>{ return "Are you sure you want to exit?"; };
attached(){
window.addEventListener("onbeforeunload", this.refreshClicked);
}
Run Code Online (Sandbox Code Playgroud)
但是它不起作用,但是,如果我们将 return 语句替换为console.log("clicked")我可以看到侦听器可以正常工作。
有什么帮助吗?
首先,如果您通过 添加事件处理程序window.addEventListener,则on在这种情况下不要使用前缀。所以要么是:
attached() {
window.addEventListener('beforeunload', this.refreshClicked);
}
Run Code Online (Sandbox Code Playgroud)
或较旧的,不推荐的语法:
attached() {
window.onbeforeunload(this.refreshClicked);
}
Run Code Online (Sandbox Code Playgroud)
其次,您需要returnValue在Eventobject上设置属性并返回相同的字符串值以支持更多浏览器。要了解有关此事件(以及各种浏览器怪癖)的更多信息,请查看其 MDN 页面。
你refreshClicked应该是这样的:
this.refreshClicked = e => {
const confirmation = 'Are you sure you want to exit?';
e.returnValue = confirmation;
return confirmation;
};
Run Code Online (Sandbox Code Playgroud)