AutoTOC

Automatically creates a table of contents for all HTML-headers on a web page.

  1. // ==UserScript==
  2. // @name AutoTOC
  3. // @namespace http://runeskaug.com/greasemonkey
  4. // @description Automatically creates a table of contents for all HTML-headers on a web page.
  5. // @author Rune Skaug (greasemonkey@runeskaug.com), IzzySoft
  6. // @license CC BY (https://creativecommons.org/licenses/by/2.5/)
  7. // @include http://*
  8. // @include https://*
  9. // @version 1.9.2
  10. // @grant GM_registerMenuCommand
  11. // @grant GM.registerMenuCommand
  12. // @grant GM_addStyle
  13. // @grant GM.addStyle
  14. // @homepageURL https://codeberg.org/izzy/userscripts
  15. // @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
  16. // @run-at document-idle
  17. // ==/UserScript==
  18.  
  19. (function() {
  20. // text constants
  21. var fullTOCText = "Table of Contents";
  22. var hideBtnText = "\u00a0X\u00a0";
  23. var RXmatch = /^h[1-4]$/i; // regexp
  24. var XPmatch = "//h1|//h2|//h3|//h4"; // xpath
  25. //set the optional behaviour of the TOC box
  26. // if true, resets it to its initial state after you have selected a header - false does not reset it
  27. var resetSelect = true;
  28. // if true, shows a "Hide TOC"/close button on the left side of the bar
  29. var showHide = true;
  30. // if true, hides the TOC for all pages on current site
  31. var useCookie = true;
  32. // if true, adds menu item (Toggle TOC)
  33. var addMenuItem = true;
  34. // to check whether loading CSS is blocked by CSP
  35. var cssLoaded = false;
  36. // CSS definition
  37. cssJsToc = 'position: fixed; left: 0; right: 0; top: auto; bottom: 0; width: 100%; display: block; border-top: 1px solid #777; background: #ddd; margin: 0; padding: 3px; z-index: 9999;';
  38. cssSelect = 'font: 8pt verdana, sans-serif; margin: 0; margin-left:5px; background: #fff; color: #000; float: left; padding: 0; vertical-align: bottom;';
  39. cssOption = 'font: 8pt verdana, sans-serif; color: #000;';
  40. cssHideBtn = 'font: bold 8pt verdana, sans-serif !important; float: left; margin-left: 2px; margin-right: 2px; padding: 1px; border: 1px solid #999; background: #e7e7e7;';
  41. cssHideLink = 'color: #333; text-decoration: none; background: transparent;} #js-toc .hideBtn a:hover { color: #333; text-decoration: none; background: transparent;';
  42.  
  43. function f() {
  44. //only on (X)HTML pages containing at least one heading - excludes XML files, text files, plugins and images (displayed using minimal HTML)
  45. if (document.getElementsByTagName("html").length && ( document.getElementsByTagName('h1').length ||
  46. document.getElementsByTagName('h2').length ||
  47. document.getElementsByTagName('h3').length ||
  48. document.getElementsByTagName('h4').length )
  49. && (!useCookie || (useCookie && getCookie('autotoc_hide')!='true'))) {
  50. var aHs = getHTMLHeadings();
  51. if (aHs.length>1) { // HTML document, more than one heading.
  52. var body = document.getElementsByTagName('body')[0];
  53. body.style.marginBottom = "24px !important";
  54. GM_addStyle('@media print { #js-toc {display: none; visibility: hidden; }}\n'+
  55. '@media screen { #js-toc { '+cssJsToc+' }\n'+
  56. '#js-toc-dummy { display:none; }\n'+
  57. '#js-toc select { '+cssSelect+' }\n'+
  58. '#js-toc option { '+cssOption+' }\n'+
  59. '#js-toc .hideBtn { '+cssHideBtn+' }\n'+
  60. '#js-toc .hideBtn a { '+cssHideLink+' }\n'+
  61. '#js-toc:not(:hover) { height: 2px !important; width: 5px !important; border-radius: 5px !important; background-color: #00f !important; }'
  62. );
  63. // check whether our CSS was loaded:
  64. var dummy = document.createElement('span');
  65. dummy.id = 'js-toc-dummy';
  66. document.body.appendChild(dummy);
  67. if ( getComputedStyle(document.getElementById('js-toc-dummy')).display == 'none' ) { cssLoaded = true; }
  68. dummy.parentNode.removeChild(dummy);
  69. // Browser sniff++ - due to rendering bug(s) in FF1.0
  70. var toc = document.createElement(window.opera||showHide?'tocdiv':'div');
  71. toc.id = 'js-toc';
  72. if (showHide) {
  73. var hideDiv = document.createElement('div');
  74. hideDiv.setAttribute('class','hideBtn');
  75. var hideLink = document.createElement('a');
  76. hideLink.setAttribute("href","#");
  77. hideLink.addEventListener("click",function(){if(useCookie){document.getElementById('js-toc').style.display='none';document.cookie='autotoc_hide=true; path=/';return false;}else{document.getElementById('js-toc').style.display='none';}});
  78. hideLink.appendChild(document.createTextNode(hideBtnText));
  79. if ( !cssLoaded ) hideLink.style = cssHideLink;
  80. hideDiv.appendChild(hideLink);
  81. if ( !cssLoaded ) hideDiv.style = cssHideBtn;
  82. toc.appendChild(hideDiv);
  83. }
  84. tocSelect = document.createElement('select');
  85. tocSelect.addEventListener("change", function(){gotoAnchor(this)});
  86. tocSelect.id = 'toc-select';
  87. tocEmptyOption = document.createElement('option');
  88. tocEmptyOption.setAttribute('value','');
  89. tocEmptyOption.appendChild(document.createTextNode(fullTOCText));
  90. if ( !cssLoaded ) tocEmptyOption.style = cssOption;
  91. tocSelect.appendChild(tocEmptyOption);
  92. if ( !cssLoaded ) tocSelect.style = cssSelect;
  93. toc.appendChild(tocSelect);
  94. if ( !cssLoaded ) toc.style = cssJsToc;
  95. document.body.appendChild(toc);
  96. for (var i=0,aH;aH=aHs[i];i++) {
  97. if (aH.offsetWidth) {
  98. op = document.createElement("option");
  99. op.appendChild(document.createTextNode(gs(aH.tagName)+getInnerText(aH).substring(0,100)));
  100. var refID = aH.id ? aH.id : aH.tagName+'-'+(i*1+1);
  101. op.setAttribute("value", refID);
  102. if ( !cssLoaded ) op.style = cssOption;
  103. document.getElementById("toc-select").appendChild(op);
  104. aH.id = refID;
  105. }
  106. }
  107. }
  108. }
  109. };
  110.  
  111. function autoTOC_toggleDisplay() {
  112. if (document.getElementById('js-toc')) {
  113. // toc-bar exists
  114. if (document.getElementById('js-toc').style.display == 'none') {
  115. document.getElementById('js-toc').style.display = 'block';
  116. if (useCookie) {document.cookie = 'autotoc_hide=; path=/';}
  117. }
  118. else {
  119. document.getElementById('js-toc').style.display = 'none';
  120. if (useCookie) {document.cookie = 'autotoc_hide=true; path=/';}
  121. };
  122. } else {
  123. // toc-bar not created yet, clear hide-cookie and run main script
  124. if (useCookie) {document.cookie = 'autotoc_hide=; path=/';}
  125. f();
  126. }
  127. }
  128.  
  129. function flash(el,rep,delay) {
  130. for (var i=rep;i>0;i--) {
  131. window.setTimeout(function(){el.style.background="#ff7";},delay*i*2);
  132. window.setTimeout(function(){el.style.background=elbg;},delay*((i*2)+1));
  133. }
  134. }
  135. function gotoAnchor(selectEl) {
  136. if(selectEl) {
  137. el = document.getElementById(selectEl.value);
  138. elbg = el.style.background;
  139. location.href = '#' + selectEl.value;
  140. flash(el,5,100);
  141. if ( resetSelect ) { selectEl.selectedIndex = 0; }
  142. }
  143. }
  144.  
  145. function getHTMLHeadings() {
  146. function acceptNode(node) {
  147. if (node.tagName.match(RXmatch)) { if (node.value+''!='') { return NodeFilter.FILTER_ACCEPT; } }
  148. return NodeFilter.FILTER_SKIP;
  149. }
  150. outArray = new Array();
  151. // XPath
  152. if (document.evaluate) {
  153. var nodes = document.evaluate(XPmatch, document, null, XPathResult.ANY_TYPE, null);
  154. var thisHeading = nodes.iterateNext();
  155. var j = 0;
  156. while (thisHeading) {
  157. if (thisHeading.textContent+''!='') {
  158. outArray[j++] = thisHeading;
  159. }
  160. thisHeading = nodes.iterateNext();
  161. }
  162. }
  163. // document.getElementsByTagName - slow! :)
  164. else {
  165. var els = document.getElementsByTagName("*");
  166. var j = 0;
  167. for (var i=0,el;el=els[i];i++) {
  168. if (el.tagName.match(RXmatch)) outArray[j++] = el;
  169. }
  170. }
  171. return outArray;
  172. }
  173. function gs(s){
  174. s = s.toLowerCase();
  175. var ret = "";
  176. for (var i=1; i<(s.substring(1)*1);i++) {
  177. ret = ret + "\u00a0 \u00a0 ";
  178. }
  179. return ret;
  180. }
  181. function getInnerText(el) {
  182. var s='';
  183. for (var i=0,node; node=el.childNodes[i]; i++) {
  184. if (node.nodeType == 1) s += getInnerText(node);
  185. else if (node.nodeType == 3) s += node.nodeValue;
  186. }
  187. return s;
  188. }
  189. function getCookie(cname)
  190. {
  191. var namesep = cname + "=";
  192. var ca = document.cookie.split(';');
  193. for(var i=0, c; c=ca[i]; i++)
  194. {
  195. c = c.replace(/^\s*|\s*$/g,"");
  196. if (c.indexOf(namesep) == 0) {
  197. return c.substring(namesep.length,c.length);
  198. }
  199. }
  200. return null;
  201. }
  202. // main()
  203. if (!window.opera && addMenuItem) {
  204. GM.registerMenuCommand('AutoTOC: Toggle display', autoTOC_toggleDisplay);
  205. }
  206. f();
  207. })();