简体   繁体   中英

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. 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.

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

Somewhere in the source code of Google Meet, there is most likely an if statement checking to see if this property is true. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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