[YouTube] Auto add Text in ChatBox

Auto add Text in ChatBox.

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/455302/1121818/%5BYouTube%5D%20Auto%20add%20Text%20in%20ChatBox.js

  1. // ==UserScript==
  2. // @name [YouTube] Auto add Text in ChatBox
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.5
  5. // @description Auto add Text in ChatBox.
  6. // @author You
  7. // @include https://www.youtube.com/watch*
  8. // @include https://www.youtube.com/live_chat*
  9. // @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
  10. // @grant none
  11. // ==/UserScript==
  12. const chat = document.querySelector("#input > #input")
  13. if(localStorage.getItem('enable-words-typing') != 'false'){
  14. addText(localStorage.getItem('add-text') == null ? '#' : localStorage.getItem('add-text'))
  15. }
  16.  
  17. chat.addEventListener("keyup", e => {
  18.  
  19. if(e.key == "Enter" && htmlSetUp && localStorage.getItem('enable-words-typing') != 'false'){
  20. //テキストボックスに指定した文字を追加。
  21. addText(htmlSetUp.addTextOption.value == null ? '#' : htmlSetUp.addTextOption.value)
  22. }
  23.  
  24. })
  25.  
  26. /**
  27. *@Description 自動でチャットボックスにテキストを追加
  28. */
  29. function addText(text){
  30.  
  31. document.querySelector('#input').setAttribute("has-text" , "")
  32. chat.setAttribute("aria-invalid" , "")
  33. chat.textContent = text
  34. moveEndCaret(chat)
  35.  
  36. }
  37.  
  38. /**
  39. *@Description キャレットの位置を文末に変更
  40. */
  41. function moveEndCaret(textBox){
  42.  
  43. const selection = window.getSelection()
  44. const range = document.createRange()
  45. const offset = textBox.innerText.length
  46. range.setStart(textBox.firstChild, offset)
  47. range.setEnd(textBox.firstChild, offset)
  48. selection.removeAllRanges()
  49. selection.addRange(range)
  50.  
  51. }