Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
825 views
in Technique[技术] by (71.8m points)

javascript - How to use (or is it possible) MutationObserver to monitor window.location.pathname change?

I wonder if it is possible to use MutationObserver to monitor change in window.location.pathname (or window.location.hash).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Mutation observers observe the DOM, not objects, and are not relevant here.

Object observers cannot observe location.hash, not because location is a system object or a security risk, but because hash is a synthetic property managed internally by the equivalent of getters and setters.

In your case, you don't need any of that. You can watch for hash changes using the popState event.

window.onpopstate=function() { console.log("foo"); };

location.hash = "bar";
"foo"

I don't know what your intent is in watching for changes in location.pathname. That will cause a page reload before your handler has a chance to do anything.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...