A guide on incorporating `executeScript` in Rselenium for emulating the activation of hotkeys

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)

Answer №1

Many browsers have implemented security measures that prevent the automatic calling of extensions, which poses a challenge for scientific research tasks such as web scraping, particularly in the context of literature reviews.

To address this issue, I decided to enlist the help of a developer who created an external program capable of simulating key presses in order to call any desired extension automatically.

I have also set up a repository on GitHub for those encountering similar obstacles.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble igniting the spark in RStudio? Unfortunately, the spark_connect() function is not functioning properly. Let

After installing R-3.4.0 and rstudio-server 1.1.447 on CentOS, I encountered an issue connecting Spark in Rstudio: sc <- spark_connect(master = "local") Error in validate_java_version(master, spark_home) : Java is required to connect to Spark. Pl ...

What is the best way to remove MongoDB collections by their age or date of creation?

I have multiple MongoDB collections created on different dates, each using the date as its name: 2015-06-01 2015-06-02 2015-06-03 ... 2015-06-30 total 30 collections If I only want to keep the latest 10 collections on a given day, for example today which ...

Is there a way for me to determine the exact coordinates of all buttons on a given webpage?

I came across this piece of code, but I'm a bit unsure about where exactly I should input it and how to adjust it to locate the position of each button. Additionally, I'm curious as to where the results (coordinates) will be shown? function find ...

React Error: Unable to Call function this.state.Data.map

I'm encountering an issue with mapping objects in ReactJS. Even though I am able to fetch data, when I try to map it, I receive the following error: this.state.Data.map is not a function Here's the code snippet: import React, { Component } fro ...

What is the method for storing elements in localStorage within a ReactJs application?

Currently, I am working on learning react-redux and coding a new project. My goal is to implement a feature where clicking the Add Favorites button will push all column data to local storage. Despite reading numerous articles, none of them have provided ...

arranging a collection of images based on their values in increasing order

cardShop is a container with various images, each with its own unique ID and value attribute. These values consist of two numbers separated by a comma, such as 2000,500 or 1500,200. My goal is to sort these images in ascending order based on the first numb ...

Configuration for secondary dependencies in Tailwind

As per the guidelines outlined in the official documentation, it is recommended to configure Tailwind to scan reusable components for class names when using them across multiple projects: If you’ve created your own set of components styled with Tailwin ...

When iterating over objects in JavaScript, the loop may return undefined, while using Lodash's map

After encountering an issue with a JavaScript loop where the value was returning as null upon completion, I decided to try using lodash for the same purpose and it successfully returned the result. This is what I attempted: JavaScript: const jsRows = Ob ...

Press the option "Switch to red button" in order to transform the text color to red, and then revert back to its initial color

I am trying to implement a feature where the "convert to red button" changes the text to red in the preview paragraph, and then reverts back to the primary color according to the theme - black in the light theme, white in the blue and black background them ...

Preserve data frame characteristics following a join operation

It has come to my attention that while dplyr functions retain attributes from columns, they do not preserve the data frame's attributes. Consider the following scenario: library("dplyr") library("lubridate") #Fictitious data n = 20 df <- data.f ...

JavaScript implementation of the results sorting

I have 2 sql queries to calculate the turnover for each semester. Results from query 1: { "LRU": [ "RADOME", "RADOME", "ATSU", "MFC", "FWC", "Unspecified", "AZE", "ECP", "CMM", "ECP" ], "Client": [ 17346, ...

Transform gradient backgrounds as the mouse moves

I'm attempting to create a unique gradient effect based on the cursor position. The code below successfully changes the background color of the document body using $(document.body).css('background','rgb('+rgb.join(',')+&a ...

Analyzing multiple variables with the Kolmogorov-Smirnov

Let's analyze the distribution of two datasets using a K-S test, as explained here. First, we generate some data: set.seed(123) N <- 1000 var1 <- runif(N, min=0, max=0.5) var2 <- runif(N, min=0.3, max=0.7) var3 <- rbinom(n=N, size=1, pro ...

What is the best way to include the API body in a GET request?

I'm facing an issue with passing parameters to the body instead of the query in my code. Here's what I have attempted: const fetchData = async () => { let response = await apiCall("URL" + { "companyArr": ["SBI Life Insurance C ...

Connecting promises to build upon past outcomes

Can someone help me figure out how to access previous results in promises? I've been following the guidance on this stackoverflow thread. I had success with 2 promises, but things got tricky when I added a 3rd promise that makes a POST request to an ...

What manner must I understand this syntax?

After stumbling upon this code snippet online, I was left scratching my head: function cjsDetectionPlugin() { return { name: 'cjs-detection', moduleParsed({ id, meta: { commonjs: { isCommonJS } } }) { ...

The failure of numerous asynchronous calls in the JavaScript Facebook API is causing issues

Utilizing Facebook's Javascript API in my jquery mobile website to fetch albums and photos from a Facebook public page and display them on my website has been quite seamless. The API provides clear instructions on how to accomplish this, and I was ab ...

Adding Measurement Units to the Values in RoundSlider: A Step-by-Step Guide

I'm working on a roundslider widget and I want to display units with the values. If the value is between 0 and 999, it should show "Hz" next to it. For values between 1000 and 999999, "KHz" should be displayed, and so on. Below is the original slider ...

In the dragstart event handler, event.dataTransfer and event.originalEvent will consistently be null

I have been working on developing drag and drop directives for angularJS by referencing this informative post: However, I am facing an issue where the dataTransfer and originalEvent are consistently null within the dragstart event handler, preventing me f ...

Angular Directives in Error

Help needed with creating a custom directive in Angular. Seeking guidance :) I am trying to display the content from 'directive.html' within the 'app-info' directive. The code functions properly without the directive, indicating a mist ...