Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

javascript - 离开页面之前的JavaScript(JavaScript before leaving the page)

I want to make a confirmation before user leaving the page.

(我想在用户离开页面之前做出确认。)

If he says ok then it would redirect to new page or cancel to leave.

(如果他说好,那么它将重定向到新页面或取消离开。)

I tried to make it with onunload

(我尝试使用onunload来实现它)

<script type="text/javascript">
function con() {
    var answer = confirm("do you want to check our other products")
    if (answer){

        alert("bye");
    }
    else{
        window.location = "http://www.example.com";
    }
}
</script>
</head>

<body onunload="con();">
<h1 style="text-align:center">main page</h1>
</body>
</html>

But it confirm after page already closed?

(但它确认页面已经关闭后?)

How to do it properly?

(怎么做得好?)

It would be even better if someone shows how to do it with jQuery?

(如果有人用jQuery演示如何做到这一点会更好吗?)

  ask by kd7 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

onunload (or onbeforeunload ) cannot redirect the user to another page.

(onunload (或onbeforeunload )无法将用户重定向到另一个页面。)

This is for security reasons.

(这是出于安全原因。)

If you want to show a prompt before the user leaves the page, use onbeforeunload :

(如果要在用户离开页面之前显示提示,请使用onbeforeunload :)

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Or with jQuery:

(或者使用jQuery:)

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page.

(这只会询问用户是否要离开页面,如果他们选择留在页面上,则无法重定向。)

If they select to leave, the browser will go where they told it to go.

(如果他们选择离开,浏览器将转到他们告诉它去的地方。)

You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload ):

(您可以在卸载页面之前使用onunload来执行操作,但是您无法从那里重定向(Chrome 14+会在onunload阻止警报):)

window.onunload = function() {
    alert('Bye.');
}

Or with jQuery:

(或者使用jQuery:)

$(window).unload(function(){
  alert('Bye.');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...