如何检测SPA中的URL更改 [英] How to detect URL changes in SPA

查看:124
本文介绍了如何检测SPA中的URL更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案应该是纯Javascript - 没有外部库和框架。

Solution should be in pure Javascript - No external library and frameworks.

在SPA中,所有内容都使用路由机制进行路由。
即使网址的任何部分发生变化,我也只想听一个偶数(不仅是哈希。我想要检测的任何变化)

In SPA, Everything gets routed using routing mechanism. I just want to listen to an even whenever any part of url changes (Not only hash. Any change I want to detect)

以下是SPA的例子,

https://www.google.in/
https://www.google.in/women 
https://www.google.in/girl 

现在每当网址从<更改时a href =https://www.hopscotch.in/ =noreferrer> https://www.hopscotch.in/ 到 https://www.hopscotch.in/women ,我想抓住那个事件。

Now whenever url changes from https://www.hopscotch.in/ to https://www.hopscotch.in/women, I want to capture that event.

我试过了,

window.addEventListener("hashchange",function(event){
    console.log(this); // this gets fired only when hash changes
});


推荐答案

在正常情况下,没有事件发生时URL更改。您正在加载新文档(尽管您有加载等等)

Under normal circumstances, there isn't an event when the URL changes. You are loading a new document (although you have load and so on)

如果您要设置新的URL使用JavaScript(即使用 pushState )然后没有事件,但你不需要一个,因为你已经明确地在它周围编写代码,所以你只需添加你需要的任何其他代码。

If you are setting a new URL with JavaScript (i.e. with pushState) then there isn't an event, but you don't need one because you're already explicitly writing code around it, so you just add whatever else you need to that code.

你会得到一个 popstate 事件,如果URL通过浏览器后退按钮或类似内容通过pushState历史记录更改回来。

You'll get a popstate event if the URL changes back though your pushState history via the browser back button or similar.

因此,没有好的通用方法可以挂钩每个SPA。你最接近的将是使用 setInterval 并检查 location.href 的值以查看它是否发生了变化最后一次检查。

Consequently, there is no good generic way to hook into every SPA. The closest you could come would be to use setInterval and inspect the value of location.href to see if it changed since the last inspection.

这篇关于如何检测SPA中的URL更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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