是可以用户刷新网页并同时重定向到另一个URL

Is is possible for user refresh webpage and redirect to another url at same time?

本文关键字:重定向 另一个 URL 用户 刷新 网页      更新时间:2023-09-26

现在,我正在尝试通过重定向到项目中的其他 url 功能来实现刷新机制。

我的重新加载回调如下所示:

<script type="text/javascript">
  var connection; // connection will build up in the following code 
  $(window).bind('beforeunload',function(){
  connection.close();
  console.log(connection.readyState);
  //I try to redirect from here
  window.location.replace("http://stackoverflow.com");
  return 'are you sure you want to leave?';
  });
</script>

下面的代码不起作用。 我的问题有什么可能的解决方案吗?

谢谢!

您可以使用confirm对话框询问用户是否希望离开。

如果用户希望离开,您可以使用location.reload()刷新页面,然后通过分配新 href 的值将他重定向到location.href新目标。

但是,当然,如果您无论如何都要将用户重定向到其他地方,则不需要先前的操作(刷新),但这取决于您:

var reload = confirm("are you sure you want to leave?");
if(reload)
{
    location.reload(); // Refresh the site, not needed really.
    location.href = "http://stackoverflow.com"; // Redirect.
}

编辑

为了在重新加载时实现它,我们可以使用卸载(未测试):

当窗口卸载其内容和资源时,将引发 unload 事件。资源删除在发生卸载事件后进行处理。

这样的事情应该有效:

$(window).unload(function()
{
    var reload = confirm("are you sure you want to leave?");
    if(reload)
    {
        location.reload(); // Refresh the site, not needed really.
        location.href = "http://stackoverflow.com"; // Redirect.
    }
});

请注意,某些浏览器(如 Chrome)禁止您在卸载时发出警报,也许确认是否属于该类别,但请随时尝试。