Skip to content

Instantly share code, notes, and snippets.

@hidao80
Last active September 3, 2023 03:03
Show Gist options
  • Save hidao80/1a210fdb16e24923c0fd8c74eaf4c403 to your computer and use it in GitHub Desktop.
Save hidao80/1a210fdb16e24923c0fd8c74eaf4c403 to your computer and use it in GitHub Desktop.
ChatWorkの投稿自動読み上げbookmarklet
/**
* Copyright (c) 2022 hidao80
* Released under the MIT license
* https://opensource.org/licenses/mit-license.php
*/
// bookmarklet:
// javascript:(()=>{let msg=e=>{let msg=document.querySelectorAll("._message");return msg[msg.length-1]},lastMsg=e=>msg().getElementsByTagName("pre")[0].textContent,lastMsgId=e=>msg().dataset.mid,speakerName=e=>{let name=document.querySelectorAll("._speakerName");return name[name.length-1].textContent},old_id=lastMsgId();const synth=new SpeechSynthesisUtterance;speechSynthesis.onvoiceschanged=()=>{const voices=speechSynthesis.getVoices();if(navigator.userAgent.toLowerCase().indexOf("edg")>-1)for(let i=0;i<voices.length;i++)voices[i].name.indexOf("Nanami")>-1&&(synth.voice=voices[i])},setInterval(()=>{let new_id=lastMsgId();old_id!=new_id&&(old_id=new_id,speechSynthesis.cancel(),synth.text=speakerName()+"さんの投稿。"+lastMsg().replace(/https?:\/\/[\w/:%#\$&\?\(\)~\.=\+\-]+/g," "),speechSynthesis.speak(synth))},1e3)})();
(() => {
let msg = e => {
// 投稿のリストの取得
let msg = document.querySelectorAll("._message");
return msg[msg.length - 1]; // 最後の一つを返す
}
let lastMsg = e => {return msg().getElementsByTagName("pre")[0].textContent;} // 最後の投稿の文章を返す
let lastMsgId = e => {return msg().dataset.mid;} // 最後の投稿のメッセージIDを返す
let speakerName = e => {
// 最後の投稿者名を返す
let name = document.querySelectorAll("._speakerName");
return name[name.length - 1].textContent;
}
let old_id = lastMsgId();
const synth = new SpeechSynthesisUtterance(); // 読み上げオブジェクトをあらかじめ一つだけ用意しておく
// 声色オブジェクトが読み込まれたとき、Edgeの場合は声色を「Nanami」にする(でふぉるとは「Google 日本語」)
speechSynthesis.onvoiceschanged = () => {
const voices = speechSynthesis.getVoices();
if (navigator.userAgent.toLowerCase().indexOf('edg') > -1) {
for (let i = 0; i < voices.length; i++) {
if (voices[i].name.indexOf("Nanami") > -1) {
synth.voice = voices[i];
}
}
}
};
setInterval(() => {
// 最後の投稿IDを1秒毎に確認し、変更があったら最後の投稿と投稿者名を読み上げる
let new_id = lastMsgId();
if (old_id != new_id) {
old_id = new_id;
speechSynthesis.cancel();
synth.text = speakerName() + "さんの投稿。"+ lastMsg().replace(/https?:\/\/[\w/:%#\$&\?\(\)~\.=\+\-]+/g, " ");
speechSynthesis.speak(synth);
}
}, 1000);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment