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.1
  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. // @grant none
  11. // ==/UserScript==
  12.  
  13. (function () {
  14. 'use strict';
  15.  
  16. function htmlToElement(html) {
  17. var template = document.createElement('template');
  18. html = html.trim(); // Never return a text node of whitespace as the result
  19. template.innerHTML = html;
  20. return template.content.firstChild;
  21. }
  22.  
  23. console.log('Replacing time format...');
  24. var timeSpans = document.evaluate('//div[@class="user-action-time"]//span', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  25. for (var i = 0; i < timeSpans.snapshotLength; i++) {
  26. var timeSpan = timeSpans.snapshotItem(i);
  27. timeSpan.innerText = timeSpan.title;
  28. }
  29.  
  30. console.log('Adding share buttons...');
  31. var answerDivs = document.evaluate('//div[@id="answers"]/div[contains(@id, "answer-")]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  32. for (var j = 0; j < answerDivs.snapshotLength; j++) {
  33. var answerDiv = answerDivs.snapshotItem(j);
  34. var answerID = document.evaluate('./@id', answerDiv, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value;
  35. var actionDiv = document.evaluate('./div[1]/div[1]/div[1]', answerDiv, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  36. var shareLink = window.location.href.split('#')[0] + '#' + answerID;
  37. var shareDiv = htmlToElement('<div class="py6 mx-auto"><a href="#' + answerID + '" onclick="navigator.clipboard.writeText(\'' + shareLink + '\')">🔗</a></div>');
  38. actionDiv.appendChild(shareDiv);
  39. }
  40.  
  41. })();