How to trigger the listen button on the Google-translate page using javascript?

天涯浪子 提交于 2019-12-11 00:19:01

问题


I want to add shortcuts to the Google-translate page.
Press Altc or Esc to clear the textarea; press Altj to pronounce.

This is the current user script: userscripts.org/scripts/review/110928

I do not know how to trigger the listen button on that page.

I tried:

  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("gt-src-listen"); 
  cb.dispatchEvent(evt);

but it does not work. (gt-src-listen is id of the listen button.)


回答1:


Google uses some pretty screwy code, several events seem to be required to get that button to play.

This works in Chrome:

function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent('MouseEvents'); 
    clickEvent.initEvent (eventType, true, true); 
    node.dispatchEvent (clickEvent);
}

var srcListenButton  = document.getElementById('gt-src-listen');

triggerMouseEvent (srcListenButton, 'mouseover');
triggerMouseEvent (srcListenButton, 'mousedown');
triggerMouseEvent (srcListenButton, 'mouseup');

(For now; Google continually breaks things).

Nothing works in Firefox, and those buttons have never played for me, even manually clicking, in that browser.



来源:https://stackoverflow.com/questions/7136834/how-to-trigger-the-listen-button-on-the-google-translate-page-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!