浏览器监听关闭和前进后退的事件

监听前进后退在h5的popstate出来之前是不可能做到的,现在通过popstate就能做到,MDN这么说的:

当活动历史记录条目更改时,将触发popstate事件。如果被激活的历史记录条目是通过对history.pushState()的调用创建的,或者受到对history.replaceState()的调用的影响,popstate事件的state属性包含历史条目的状态对象的副本。

需要注意的是调用history.pushState()history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()或者history.forward()方法),不同的浏览器在加载页面时处理popstate事件的形式存在差异。页面加载时Chrome和Safari通常会触发(emit )popstate事件,但Firefox则不会。

也就是说popstate可以监听pushState和replaceState包括back和go,这也是vue中路由监听的原理,代码示例:

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>demo</title>
</head>
<body>
<span class="js-news">新闻</span>
<span class="js-music">音乐</span>
<span class="js-sports">体育</span>
<span class="js-literature">文学</span>
<script>
    var locationHref = location.href;
    document.addEventListener("click", function (event) {
        var target = event.target;
        if (target.className == "js-news") {
            history.pushState("首页", "", locationHref + "/11.html");//这种history模式的路由似乎监听不到
        } else if (target.className == "js-music") {
            history.pushState("音乐", "", locationHref + "#music");
        }else if (target.className == "js-sports") {
            history.pushState("体育", "", locationHref + "#sports");
        }else if (target.className == "js-literature") {
            history.pushState("文学", "", locationHref + "#literature");
        }
    });
    window.addEventListener("popstate", function () {
        console.log(history.state);
    })
</script>
</body>
</html>

 

关闭事件:

onbeforeunload与onunload事件

区别:


1)异同点
相同点:
onunload,onbeforeunload都是在刷新或关闭时调用,可以在<script>脚本中通过window.onunload来指定或者在<body>里指定。

不同点:
a)onbeforeunload在onunload之前执行 ,它还可以阻止onunload的执行。
b)onbeforeunload是正要去服务器读取新的页面时调用,此时还没开始读取;nunload则已经从服务器上读到了需要加载的新的页面,在即将替换掉当前页面时调用 。
c)onbeforeunload是可以阻止页面的更新和关闭的。但是onunload不能。
onload、onbeforeunload、onunload事件的执行顺序:
打开页面时:只执行onload
关闭页面时:先onbeforeunload,后onunload
刷新页面时:先onbeforeunload,后onunload,再onload

2)onbeforeunload、onunload事件

触发于:
a)关闭浏览器窗口
b)通过地址栏或收藏夹前往其他页面的时候
c)点击返回,前进,刷新,主页其中一个的时候
d)点击 一个前往其他页面的url连接的时候
e)调用以下任意一个事件的时候:click,document write,document open,document close,window close ,window navigate ,window NavigateAndFind,location replace,location reload,form submit.
f)当用window open打开一个页面,并把本页的window的名字传给要打开的页面的时候。
g)重新赋予location.href的值的时候。
h)通过input type=”submit”按钮提交一个具有指定action的表单的时候。

可以用在以下元素:
BODY, FRAMESET, window
浏览器支持:
IE4+/Win, Mozilla 1.7a+, Netscape 7.2+, Firefox0.9+

3)解决刷新页面时不调用onbeforeunload

4)onbeforeunload阻止页面的更新和关闭
onbeforeunload="return '是否现在离开此页面';">

 

问题:如何监听history形式的路由,希望知道的大佬留言赐教

参考:

1.https://developer.mozilla.org/zh-CN/docs/Web/API/Window/popstate_event   MDN:popstate

2.https://www.cnblogs.com/shuiyi/p/5115188.html  图解用HTML5的popstate如何玩转浏览器历史记录

3.http://www.jquerycn.cn/a_10963  onbeforeunload与onunload事件的区别

 

posted @ 2021-03-01 09:35  洛晨随风  阅读(1922)  评论(0编辑  收藏  举报