Skip to content

Instantly share code, notes, and snippets.

@yesasha
Created February 15, 2018 15:18
Show Gist options
  • Save yesasha/56fa08d3ccbafdeb701f9d57350204af to your computer and use it in GitHub Desktop.
Save yesasha/56fa08d3ccbafdeb701f9d57350204af to your computer and use it in GitHub Desktop.
Calls location.replace instead of the default assigning behavior, so that history is not populated with each followed link
// Location replacer
addEventListener('click', function (event) {
// Create .which property if not exists
// As far as I've tested, it exists in all modern browsers
if (!event.which && event.button) {
if (event.button & 1) {
event.which = 1;
} else if (event.button & 4) {
event.which = 2;
} else if (event.button & 2) {
event.which = 3;
}
}
// Return, if not left mouse button
if (event.which !== 1) {
return;
}
// Scan for parent <a> element since it can contain other child elements
var target = event.target;
do {
if (target.tagName === 'A') {
// Check if we are going to the same page. target.origin is not supported in Internet Explorer
var targetUrl = target.protocol + '//' + target.host + (target.port ? ':' + target.port : '') + target.pathname + target.search;
// <del>var locationUrl = location.origin + location.pathname + location.search;</del>
// location.origin is null in firefox when on "file:" protocol
// So need to construct an url manually
var locationUrl = location.protocol + '//' + location.host + (location.port ? ':' + location.port : '') + location.pathname + location.search;
if (targetUrl === locationUrl && target.hash !== location.hash) {
// In some browsers, like firefox, without preventDefault glitches may appear
event.preventDefault();
// Replace instead of assign. This is the main point!
location.replace(target.href);
}
break;
}
} while (target !== this && (target = target.parentElement)) // Don't scan higher than element to which the listener is assigned and not higher than <html>
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment