3

I would like to create and fire a KeyPress Event through a userscript in Greasemonkey but I observed that the createEvent's isTrusted is set to false all the time.

isTrusted is read-only property but I read that it can be set to True by extensions like Greasemonkey but it's not working for me.

Is there a way to set isTrusted to true?.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Revo
  • 47
  • 1
  • 4

2 Answers2

2

No. You cannot currently do this with Greasemonkey. For the most part, Greasemonkey just runs javascript, and javascript can't set isTrusted. It would defy the spec and defeat the whole purpose of trusted events.

That said, theoretically, a Firefox add-on should be able to spoof isTrusted, but Greasemonkey has not extended that capability to its users.

There is a feature request to add isTrusted capability to Greasemonkey. You can go there and add your voice to the discussion, or you can fork the Greasemonkey code and add the capability yourself.




There is a related question for Google Chrome, but spoofing isTrusted may not be possible in that browser, even for extensions.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
1

Theoretically, You could create a trusted event with a WebSocket that javascript uses to communicate to a python script running in the background with would press the key, but that's a lot of code.

Python Code:

import asyncio
import websockets
import pyautogui
async def watchlist(websocket, path):
    while (1==1):
        key = await websocket.recv()
        pyautogui.press(key)

start_server = websockets.serve(watchlist, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()



Js Code to press key:

ws = new WebSocket("ws://localhost:8765")
function sendkey(key){
     ws.send(key)
}
sendkey('a')
Bob Hang
  • 61
  • 5
  • 1
    Any ground for this claim? I don't see anything that would make this possible. – Kaiido Dec 09 '19 at 03:16
  • Python code: import asyncio import websockets import pyautogui async def watchlist(websocket, path): while (1==1): key = await websocket.recv() pyautogui.press(key) start_server = websockets.serve(watchlist, "localhost", 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() – Bob Hang Dec 10 '19 at 01:51
  • And how does this help in overriding the frozen `EventInstance.isTrusted`? – Kaiido Dec 10 '19 at 01:52
  • Because when python simulates a keypress, it creates a trusted event for Chrome – Bob Hang Dec 10 '19 at 23:57
  • but will this work on a background page or tab? – Ciprian David Nov 09 '21 at 16:58