how to use executeScript in Rselenium as a way to simulate pressing hotkeys

48 Views Asked by At

RSelenium is a great package for web interface using R, but lacks functionality on the use of hotkeys as a way to run external functions or for programmatically activate extensions.

One possibility I am considering is the use of a javascript command that simulates pressing a set of keys, which will call a given browser function or an extension.

I tested the use of javascript in Rselenium, which works seemly, but I have not yet found the javascript code that will simulate the pressing of keys. I found several options on the web, none of which works.

Does anyone knows the javascript code needed to simulate the pressing of say "control" + "shif" + "r".

    library(RSelenium)
    library(netstat)

    #Open browset
    rD <- rsDriver(port = free_port(), browser ="chrome",chromever = "latest", verbose = F)
    remDr <- rD$client

    url = "https://stocktwits.com/symbol/NZDCHF"
    remDr$navigate(url) 

    # test fucntionailitty using java script..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)

  #Attemt 6
  script <- 'var event = new KeyboardEvent("keydown", { key: "a", ctrlKey: true, shiftKey: true });
       document.dispatchEvent(event);'
    remDr$executeScript(script)
1

There are 1 best solutions below

0
Camilo On

It turns out that for security reasons most browsers do not allow the calling of extensions programmatically. This is a major problem for valid scientific endeavors that require web-scrapping, like literature reviews.

As such I paid a developer and the solution was to create an external program that allows the automatic simulation of pressing hotkets that call any given extension.

I created a repository in github , for any facing similar problems.