检测URL变化(无窗卸载) [英] Detect URL changes (without window unload)

查看:288
本文介绍了检测URL变化(无窗卸载)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要添加一个监听器网址变更前事件,可以访问旧的URL。 window.onbeforeunload 不火,如果页面没有加载(AJAX驱动页)。

I want to add a listener to "before URL change" event, with access to the old URL. window.onbeforeunload does not fire if the page does not reload (AJAX driven pages).

这发生在YouTube视频页面,当你点击在右侧导航栏的另一个视频,例如。

This happens on YouTube video pages, when you click on another video in the right navigation column, for example.

我已经阅读这帖子,这民意测验 window.location的。但是,这并没有捕捉到旧的URL。

I have read this post, which polls window.location. But this does not capture the old URL.

这是一个Chrome扩展。我正在寻找一种方法在JavaScript中的URL改变之前被检测到。

This is for a Chrome extension. I'm looking for a way to detect before URL change in javascript.

推荐答案

有关使用历史 API AJAX驱动的网页(其中大部分,包括YouTube),你可以拼接成 history.pushState

For AJAX-driven pages that use the history API (most of them, including YouTube), you can splice into history.pushState.

有关Chrome浏览器,旧的URL将在 SPF-引荐属性。 (另外, location.href 将仍然被设置为旧的URL,而pushState被解雇了。)

For Chrome, the old url will be in the spf-referer property. (Also, the location.href will still be set to the old URL while pushState is firing, too.)

所以,code像这样将工作:

So code like this will work:

var H               = window.history;
var oldPushState    = H.pushState;
H.pushState         = function (state) {
    if (typeof H.onpushstate == "function") {
        H.onpushstate ({state: state} );
    }
    return oldPushState.apply (H, arguments);
}
window.onpopstate = history.onpushstate = function (evt) {
    console.log ("Old URL: ", evt.state["spf-referer"]);
}

需要注意的是,因为你需要覆盖的目标页面的 pushState 功能,您必须的这code的内容的脚本。

Note that, because you need to override the target page's pushState function, you must inject this code from your content script.

这篇关于检测URL变化(无窗卸载)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆