6

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;

  // ignore href="#" pseudo-links
  if (target.getAttribute('href') === '#')
    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);

0

You must log in to answer this question.

Browse other questions tagged .