且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测SPA中的URL更改

更新时间:2022-01-02 09:32:34

在正常情况下,没有事件发生时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.