Better Stack Overflow

Replace time format and add share button to each answer

As of 2022-01-07. See the latest version.

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