AO3: Get Current Chapter Word Count

Counts and displays the number of words in the current chapter

当前为 2023-07-14 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name AO3: Get Current Chapter Word Count
  3. // @namespace https://github.com/w4tchdoge
  4. // @version 1.0.1-20230629_123742
  5. // @description Counts and displays the number of words in the current chapter
  6. // @author w4tchdoge
  7. // @homepage https://github.com/w4tchdoge/MISC-UserScripts
  8. // @match *://archiveofourown.org/*
  9. // @icon https://archiveofourown.org/favicon.ico
  10. // @license AGPL-3.0-or-later
  11. // ==/UserScript==
  12.  
  13. (function () {
  14. 'use strict';
  15.  
  16. // Save current page URL to a var
  17. const currPG_URL = window.location.href;
  18.  
  19. // Execute script only on multi-chapter works AND only when a single chapter is being viewed
  20. if (currPG_URL.includes('works') && currPG_URL.includes('chapters')) {
  21.  
  22. function Word_Counter(content) {
  23. // function adapted from https://github.com/Kirozen/vsce-wordcounter/blob/master/src/wordCounter.ts
  24.  
  25. const WORD_RE = /[\S]+/g;
  26.  
  27. if (!content) {
  28. return 0;
  29. }
  30.  
  31. const matches = content.match(WORD_RE);
  32. if (matches) {
  33. return matches.length;
  34. }
  35. return 0;
  36. }
  37.  
  38. function numberWithCommas(x) {
  39. // function taken from https://stackoverflow.com/a/2901298/11750206
  40.  
  41. var parts = x.toString().split('.');
  42. parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  43. return parts.join(".");
  44. }
  45.  
  46.  
  47. // Get the HTML element containing the chapter's text content
  48. var text_node = document.querySelector('[role="article"]');
  49.  
  50. // Extract the text content from the HTML element
  51. var text = text_node.innerText.replace(/chapter text\n\n/gmi, '');
  52.  
  53. // Count the number of words
  54. var word_count = numberWithCommas(Word_Counter(text));
  55.  
  56. // console.log(text);
  57. // console.log(word_count);
  58.  
  59. // Create element with the text "Words in Chapter"
  60. var chap_word_count_text = Object.assign(document.createElement('dt'), {
  61. id: 'chapter_words_text',
  62. className: 'chapter_words',
  63. innerText: 'Words in Chapter:'
  64. });
  65.  
  66. // Create element with the word count of the chapter
  67. var chap_word_count_num = Object.assign(document.createElement('dd'), {
  68. id: 'chapter_words_num',
  69. className: 'chapter_words',
  70. innerText: word_count
  71. });
  72.  
  73. // Get the element where the stats are displayed
  74. const stats_elem = document.querySelector('#main dl.work.meta.group dl.stats');
  75.  
  76. // Append the created elements after the element containing the total word count of the fic
  77. stats_elem.querySelector('dd.words').after(chap_word_count_text, chap_word_count_num);
  78. }
  79.  
  80. })();