How to detect if URL has changed after hash in JavaScript

后端 未结 17 1436
無奈伤痛
無奈伤痛 2020-11-22 17:02

How can I check if a URL has changed in JavaScript? For example, websites like GitHub, which use AJAX, will append page information after a # symbol to create a unique URL w

相关标签:
17条回答
  • 2020-11-22 17:53

    Found a working answer in a separate thread:

    There's no one event that will always work, and monkey patching the pushState event is pretty hit or miss for most major SPAs.

    So smart polling is what's worked best for me. You can add as many event types as you like, but these seem to be doing a really good job for me.

    Written for TS, but easily modifiable:

    const locationChangeEventType = "MY_APP-location-change";
    
    // called on creation and every url change
    export function observeUrlChanges(cb: (loc: Location) => any) {
      assertLocationChangeObserver();
      window.addEventListener(locationChangeEventType, () => cb(window.location));
      cb(window.location);
    }
    
    function assertLocationChangeObserver() {
      const state = window as any as { MY_APP_locationWatchSetup: any };
      if (state.MY_APP_locationWatchSetup) { return; }
      state.MY_APP_locationWatchSetup = true;
    
      let lastHref = location.href;
    
      ["popstate", "click", "keydown", "keyup", "touchstart", "touchend"].forEach((eventType) => {
        window.addEventListener(eventType, () => {
          requestAnimationFrame(() => {
            const currentHref = location.href;
            if (currentHref !== lastHref) {
              lastHref = currentHref;
              window.dispatchEvent(new Event(locationChangeEventType));
            }
          })
        })
      });
    }
    

    Usage

    observeUrlChanges((loc) => {
      console.log(loc.href)
    })
    
    0 讨论(0)
  • 2020-11-22 17:55

    You are starting a new setInterval at each call, without cancelling the previous one - probably you only meant to have a setTimeout

    0 讨论(0)
  • 2020-11-22 17:57

    In modern browsers (IE8+, FF3.6+, Chrome), you can just listen to the hashchange event on window.

    In some old browsers, you need a timer that continually checks location.hash. If you're using jQuery, there is a plugin that does exactly that.

    0 讨论(0)
  • 2020-11-22 17:57

    Look at the jQuery unload function. It handles all the things.

    https://api.jquery.com/unload/

    The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

    $(window).unload(
        function(event) {
            alert("navigating");
        }
    );
    
    0 讨论(0)
  • 2020-11-22 17:58

    Another simple way you can do this is by adding a click event, through a class name to the anchor tags on the page to detect when it has been clicked, then you can now use the window.location.href to get the url data which you can use to run your ajax request to the server. Simple and Easy.

    0 讨论(0)
提交回复
热议问题