V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
Aoliz
V2EX  ›  JavaScript

如何监听 location.href 这个值发生了变化?

  •  
  •   Aoliz · 2016-01-06 20:33:46 +08:00 · 14906 次点击
    这是一个创建于 3004 天前的主题,其中的信息可能已经有所发展或是发生改变。
    目前用循环判断,感觉有点....

    Google 了一番,没有找到答案,来求问 V 友。

    ----
    项目背景
    一个 Chrome 插件给当前页面注入了 JS ( content script),需要根据 URL 变化来做一些事情。
    10 条回复    2016-01-07 08:57:23 +08:00
    jarlyyn
        1
    jarlyyn  
       2016-01-06 20:43:34 +08:00 via Android
    记得有 history.js ?
    Lpl
        2
    Lpl  
       2016-01-06 20:54:57 +08:00 via Android
    不能记录上一次的 location jref 么,然后做对比?
    Aoliz
        3
    Aoliz  
    OP
       2016-01-06 20:56:59 +08:00
    @Lpl 所以需要有个循环( setTimeout ) 一直去比较?现在就是这么做的
    billlee
        5
    billlee  
       2016-01-06 21:06:53 +08:00
    onhashchange, beforeunload?
    AngularJS 有这个功能,你可以看看是怎么实现的
    oott123
        6
    oott123  
       2016-01-06 21:21:02 +08:00   ❤️ 1
    href 如果是 hash 部分变了,有 hashchange
    如果不是 hash 部分,页面会重新加载,有 beforeunload / unload
    如果是使用 history api 改动,有 history.onpushstate / history.onpopstate
    des
        7
    des  
       2016-01-06 21:25:28 +08:00
    location.__defineSetter__("herf",function(){debugger;})
    这样???
    zkd8907
        8
    zkd8907  
       2016-01-06 21:33:33 +08:00
    老旧版本的浏览器还是要用 setTimeout 的,新的浏览器就可以参考楼上的。
    metrue
        9
    metrue  
       2016-01-06 23:43:34 +08:00   ❤️ 1
    window.addEventListener('hashchange', function() { });
    hkongm
        10
    hkongm  
       2016-01-07 08:57:23 +08:00   ❤️ 1
    historyAPI 优选,其次 hashcange 事件
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1187 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:09 · PVG 07:09 · LAX 16:09 · JFK 19:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.