Prevent URL changes

Getting an example will be difficult, but ultimately I have some links, that when clicked, load some dynamic ajax content. This function I cannot touch. This makes the URL (e.g. on a homepage) update from
sitehere.com/
to
sitehere.com/~board/homepage-latest-news/post/sit-cras-ipsum-bibendum

This is not something I can control. However, I am running a separate event on top of that which also runs on click, and I’m trying to remove the stuff it does to the URL. I’ve tried various SO threads, and this is my latest attempt.

$(".latest-news article .fsPostLink").on("click", function(e) {
    if (window.location.href.indexOf('~board') > 0) {
      var newURL = location.href.split("~")[0];
      window.history.pushState('object', document.title, newURL);
      console.log("running");
    }
  // more stuff
});

I get the console log but it’s not working as intended.

Hi Ryan,

What is happening in your case?

I didn’t attempt to replicate the Ajax part, but that code should change the URL to:

sitehere.com/~board/homepage-latest-news/post/sit-cras-ipsum-bibendum/sitehere.com/

right? And I guess this is not what was intended.

Are you trying to remove all of the ~board/homepage-latest-news/post/sit-cras-ipsum-bibendum/ part?

Yes :slight_smile: although depending on how difficult this is I may just end up doing this a different way. The clicking was to determine if a video would load in the ajax. I am doing a different method now to determine if there’s a video. But I’m still interested in what I did wrong here :slight_smile: .

I just got my code working how I want it, so if this is too much effort, just move on :slight_smile: . I ended up not needing to modify the URL.

You need to make sure the new URL you are passing to the pushState method begins with a slash, as otherwise it will be resolved as a relative URL.

In your case, this should do the trick:

window.history.pushState({}, '', '/')
1 Like

That’s the ticket! Thanks a lot :smiley: .

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.