0

I need JavaScript to check for any changes in the URL address bar. These changes would not be caused by any clicks or refreshes. I've tried using the solution supplied by this answer:

Detect changes on the url

I am just testing this code and it doesn't work:

setInterval(function() {
   console.log(location.href);  
}, 2000);

No matter what changes I make to the address bar URL, the location.href that is outputted always stays the same. Any ideas what I could be doing wrong? Thanks!

Ele
  • 33,468
  • 7
  • 37
  • 75
drothhello
  • 3
  • 1
  • 3
  • Are you just typing in the address bar without hitting Enter? If that's all you're doing, location.href wouldn't change. – kshetline Mar 09 '18 at 03:29
  • Check out this link: https://developer.mozilla.org/en-US/docs/Web/API/Window/location – Leet Hudka Mar 09 '18 at 03:48
  • @kshetline Yes, that's exactly what I'm doing. Does location.href only work if the URL was changed by changing something in the DOM? – drothhello Mar 09 '18 at 03:57
  • @LeetHudka Thanks I'm about to check it out – drothhello Mar 09 '18 at 03:58
  • It wouldn't necessarily require changing something in the DOM, but you'd at least have to hit Enter on the address bar before an update occurred from typing there. – kshetline Mar 09 '18 at 04:00
  • @kshetline Gotcha, well in the actual app, the URL will only be changed as soon as someone starts typing in an input field. They wouldn't be pressing enter. What they type in is added to the URL at the end. Would location.href detect that change? – drothhello Mar 09 '18 at 04:03
  • You can certainly track changes in an input field without the user pressing Enter, but if you're adding what's typed by the user onto the end of the current URL, wouldn't you be doing something like `location.href += newChars`, in which case you'd already know you were updating location.href? – kshetline Mar 09 '18 at 04:07
  • @kshetline Ahh, well you see, I have just come in to make a tweak on someone else's Squarespace site. I don't have access to the original code. So, I really have no idea how they originally handled adding text to the URL. I just need to know how to get JavaScript to listen to changes in the URL. It doesn't have to listen to anything in the DOM. – drothhello Mar 09 '18 at 04:15

0 Answers0