Skip to main content
4 of 9
fix for an elusive bug when clicking href="#" pseudo-links'
user3840170
  • 385
  • 1
  • 10

Faster Answer Links

This is a convenience user script. It prevents page reloading when following links to answers that happen to be present on the same page, and to their comments; instead, it simply scrolls to the link target on the current page.

// ==UserScript==
// @name     Stack Exchange: Faster Answer Links
// @grant    none
// @run-at   document-start
// @match    https://*.stackexchange.com/*
// @match    https://*.superuser.com/*
// @match    https://*.stackoverflow.com/*
// @match    https://*.mathoverflow.net/*
// @match    https://*.serverfault.com/*
// @match    https://*.askubuntu.com/*
// @match    https://stackapps.com/*
// @exclude  https://chat.stackexchange.com/*
// @exclude  https://api.stackexchange.com/*
// @exclude  https://data.stackexchange.com/*
// @exclude  https://openid.stackexchange.com/*
// @exclude  https://contests.stackoverflow.com/*
// @exclude  /^https?:\/\/winterbash\d{4,}\.stackexchange\.com\//
// ==/UserScript==

// attaching to window because jQuery attaches *its* delegated
// event handlers to document, and we need to run *after* those

window.addEventListener('click', ev => {
  if (ev.defaultPrevented)
    return;

  const target = ev.target.closest(':any-link');
  if (!target)
    return;
  
  const u = new URL(target.href);
  if (u.origin !== location.origin)
    return;
  
  const insteadGoTo = target => {
    ev.preventDefault();
    location.href = target;
  };

  let m;
  
  if (/^\/(q|a|questions)\//u.test(u.pathname)
      && (m = /^#comment\d+_(\d+)$/u.exec(u.hash))) {
    if (!document.querySelector(`
      #answer-${m[1]}, #question[data-questionid="${m[1]}"]`))
      return;
    return insteadGoTo(u.hash);
  }
  
  if (m = /^\/(?:a|questions\/\d+\/[^\/]+)\/(\d+)(?=\/|$)/u.exec(u.pathname)) {
    if (!document.getElementById(`answer-${m[1]}`))
      return;
    if (!['', `#${m[1]}`, `#answer-${m[1]}`].includes(u.hash))
      return;
    return insteadGoTo('#answer-' + m[1]);
  }

  if (m = /^\/(?:q|questions)\/(\d+)(?=\/|$)/u.exec(u.pathname)) {
    if (!document.querySelector(`#question[data-questionid="${m[1]}"]`))
      return;
    if (!(m = /^#(?:answer-)?(\d+)$/u.exec(u.hash)))
      return;
    if (!document.getElementById(`answer-${m[1]}`))
      return;
    return insteadGoTo('#answer-' + m[1]);
  }
}, false);
user3840170
  • 385
  • 1
  • 10