Better Stack Overflow

Replace time format and add share button to each answer

As of 2024-04-26. See the latest version.

  1. // ==UserScript==
  2. // @name Better Stack Overflow
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.6
  5. // @description Replace time format and add share button to each answer
  6. // @author Landon Li
  7. // @match *://stackoverflow.com/questions/*
  8. // @match *://*.stackexchange.com/questions/*
  9. // @match *://superuser.com/questions/*
  10. // @match *://askubuntu.com/questions/*
  11. // @icon https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico
  12. // @grant none
  13. // ==/UserScript==
  14.  
  15. (function () {
  16. 'use strict';
  17.  
  18. function htmlToElement(html) {
  19. var template = document.createElement('template');
  20. html = html.trim(); // Never return a text node of whitespace as the result
  21. template.innerHTML = html;
  22. return template.content.firstChild;
  23. }
  24.  
  25. console.log('Replacing time format...');
  26. var type1TimeSpans = document.evaluate('//div[contains(@class,"user-action-time")]//span', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  27. for (var i = 0; i < type1TimeSpans.snapshotLength; i++) {
  28. var type1TimeSpan = type1TimeSpans.snapshotItem(i);
  29. type1TimeSpan.innerText = type1TimeSpan.title;
  30. }
  31.  
  32. var type2TimeSpans = document.evaluate('//span[@class="comment-date"]//span', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  33. for (var j = 0; j < type2TimeSpans.snapshotLength; j++) {
  34. var type2TimeSpan = type2TimeSpans.snapshotItem(j);
  35. type2TimeSpan.innerText = type2TimeSpan.title.split(',')[0];
  36. }
  37.  
  38. console.log('Adding share buttons...');
  39. var answerDivs = document.evaluate('//div[@id="answers"]/div[contains(@id, "answer-")]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  40. for (var k = 0; k < answerDivs.snapshotLength; k++) {
  41. var answerDiv = answerDivs.snapshotItem(k);
  42. var answerID = document.evaluate('./@id', answerDiv, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value;
  43. var actionDiv = document.evaluate('./div[1]/div[1]/div[1]', answerDiv, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  44. var shareLink = window.location.href.split('#')[0] + '#' + answerID;
  45. var shareDiv = htmlToElement('<div class="py6 mx-auto"><a href="#' + answerID + '" onclick="navigator.clipboard.writeText(\'' + shareLink + '\')">🔗</a></div>');
  46. actionDiv.appendChild(shareDiv);
  47. }
  48.  
  49. })();