[YouTube] Auto add Text in ChatBox

Auto add Text in ChatBox.

当前为 2022-11-23 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/455302/1120375/%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.2
  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. addText("#")
  14.  
  15. chat.addEventListener("keydown", e => {
  16.  
  17. if(e.key == "Enter"){
  18. //テキストボックスに指定した文字を追加。
  19. setTimeout( () => addText("#"))
  20. }
  21.  
  22. })
  23.  
  24. /**
  25. *@Description 自動でチャットボックスにテキストを追加
  26. */
  27. function addText(text){
  28.  
  29. document.querySelector('#input').setAttribute("has-text" , "")
  30. chat.setAttribute("aria-invalid" , "")
  31. chat.textContent = text
  32. moveEndCaret(chat)
  33.  
  34. }
  35.  
  36. /**
  37. *@Description キャレットの位置を文末に変更
  38. */
  39. function moveEndCaret(textBox){
  40.  
  41. const selection = window.getSelection()
  42. const range = document.createRange()
  43. const offset = textBox.innerText.length
  44. range.setStart(textBox.firstChild, offset)
  45. range.setEnd(textBox.firstChild, offset)
  46. selection.removeAllRanges()
  47. selection.addRange(range)
  48.  
  49. }