While RSelenium is a useful package for interfacing with the web using R, it falls short when it comes to utilizing hotkeys to run external functions or activate extensions programmatically.
One idea I'm exploring is using a javascript command to simulate key presses, which can then trigger specific browser functions or extensions.
I have tested using javascript in Rselenium and it works smoothly, but I have yet to find the correct javascript code to simulate key presses. Despite finding several options online, none of them have been successful.
Does anyone happen to know the exact javascript code required to simulate pressing keys like "control" + "shift" + "r"?
library(RSelenium)
library(netstat)
#Open browser
rD <- rsDriver(port = free_port(), browser ="chrome",chromever = "latest", verbose = F)
remDr <- rD$client
url = "https://stocktwits.com/symbol/NZDCHF"
remDr$navigate(url)
# Test functionality using javascript - scrolling down page.
script="window.scrollTo(0,document.body.scrollHeight);"
remDr$executeScript(script)
# Attempt 1
script=('window.addEventListener("keydown", function(e) {if (e.key === "A" && e.ctrlKey) {console.log("Hotkey pressed!");}});'))
remDr$executeScript(script)
# Attempt 2
script='window.addEventListener("keydown", function(e) {if (e.key === "A" && e.ctrlKey) {console.log("Hotkey pressed!");}});'
remDr$executeScript(script)
# Attempt 3
script <- "var event = new KeyboardEvent('keydown', { ctrlKey: true,key: 'a'}); document.dispatchEvent(event);"
remDr$executeScript(script)
# Attempt 4
script <- 'var event = new KeyboardEvent("keydown", { key: "A", code: "KeyA", ctrlKey: true });'
remDr$executeScript(script)
# Attempt 6
script <- 'var event = new KeyboardEvent("keydown", { key: "a", ctrlKey: true, shiftKey: true });
document.dispatchEvent(event);'
remDr$executeScript(script)