简体   繁体   English

KEYPRESS Function 未按预期工作

[英]KEYPRESS Function not working as expected

I am trying to make a chrome extension for Google Meet, in which when I press the space bar, the mic should turn on and vice-versa.我正在尝试为 Google Meet 制作一个 chrome 扩展,当我按下空格键时,麦克风应该打开,反之亦然。 This is my code...这是我的代码...

//Listening to key events to trigger suitable event
document.addEventListener('keypress', (event) => {
        items = document.getElementsByTagName("div");
    if (event.keyCode == 32) {
        for (i = 0; i < items.length; i++) {
            if (items[i].hasAttribute("aria-label")) {
                if (items[i].getAttribute("aria-label")
                    .includes("microphone")) {
                    items[i].click();
                }
            }
        }
    }
});

When I press the space bar, the microphone does not get affected, on the other hand, if I add an alert, that works perfectly fine.当我按下空格键时,麦克风不会受到影响,另一方面,如果我添加警报,那效果很好。 What could be the mistake?可能是什么错误?
Thanks in advance提前致谢

If I were to guess without looking at the source code for Google Meet, I would assume it was because of the isTrusted property of the event that you are trying to simulate.如果我在不查看 Google Meet 的源代码的情况下进行猜测,我会认为这是因为您尝试模拟的事件的isTrusted属性。

I was defeated by this a while back, but my understanding of it is that when the event is fired by a user, event.isTrusted is true , but when it's fired by a script event.isTrusted is false前段时间我被这个打败了,但我对它的理解是,当用户触发事件时, event.isTrustedtrue ,但是当它被脚本触发时event.isTrustedfalse

Somewhere in the source code of Google Meet, there is most likely an if statement checking to see if this property is true.在 Google Meet 的源代码中,很可能有一个if语句检查这个属性是否为真。 For example:例如:

if (event.isTrusted) {
  //toggle microphone
}

The most likely reason this is in place is so if a virus got on a user's computer it wouldn't easily be able to toggle their microphone.这样做的最可能原因是,如果病毒感染了用户的计算机,它就不能轻易地切换他们的麦克风。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM