JavaScript: How to change the hash in the address bar WITHOUT adding an entry to the history?

I am trying to expand an idea from someone else's question and run into difficulties.

The idea is to dynamically embed utm_source (from the ad campaign) in the hash URL, track the Google Analytics page, and then delete the hash. (We don’t want to save the hash, because: 1. this is a duplicate page and 2. If the bookmarking user returns, it looks like another click of the advertisement)

Here is the code that almost works:

// save the old hash
var campaignSource = "Some Banner Ad";
var oldHash = document.location.hash;

// add campaign data to the hash
document.location.hash = 'utm_source =' + escape (campaignSource);
pageTracker._setAllowAnchor (true);
pageTracker._trackPageview ();
// restore the old hash:
document.location.hash = oldHash;

The caveat is that it adds two more entries to the history (back button) with every change.

Question: How to make the browser skip the hash change history?

+3
source share
2 answers

If you want to skip adding an entry to the history, use window.location.replaceinstead

window.location.replace("#hash");

Thus, the URL address bar will be replaced instead of adding a new entry to the browser history object

+17
source

You can leave the second hash change and just use

history.back();

. "", "", , ​​ .

, .

+1

Source: https://habr.com/ru/post/1725525/


All Articles