Dictionary auto pronounce

Automatically pronounce searched word. You need manaully add website to autoplay whitelist to prevent error "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first."

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @author craftwar
// @name Dictionary auto pronounce
// @description Automatically pronounce searched word. You need manaully add website to autoplay whitelist to prevent error "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first."
// @copyright 2023, craftwar (https://craftwarblog.blogspot.com/)
// @license GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.txt
// @homepageURL https://github.com/craftwar/userscript/tree/master/Dictionary
// @version 0.1.20230501
// @namespace github.com.craftwar
// @match https://www.dictionary.com/*
// @match https://tw.dictionary.search.yahoo.com/*
// @match https://dictionary.cambridge.org/*
// @grant none
// @run-at document-idle
// ==/UserScript==

'use strict';
(() => {
  let voice;
  document.addEventListener('readystatechange', () => {
    if (document.readyState == "complete") {
      if (window.location.href.startsWith("https://dictionary.cambridge.org/"))
        voice = document.getElementsByTagName('audio')[1];
      else
        voice = document.getElementsByTagName('audio')[0];
      if (voice)
        voice.play();
    }
  });
  window.addEventListener("keydown", (event) => {
    if (event.key == "MediaPlayPause")
      voice.play();
  });
})();