Using RSelenium, I'm trying to open a new tab and scroll down. Unfortunately, I can't make this work because my browser stays at the first tab. Does anyone know how to solve this?
This is a simplied version of the code I am using:
library(RSelenium)
library(netstat)
# setup connection
rs_driver_object <- rsDriver(browser = "chrome", chromever = "138.0.7204.157",
verbose = T, port = free_port(), check = T,
phantomver = NULL,
extraCapabilities= list("-sessionTimeout 7200"))
remDr <- rs_driver_object$client
# create two tabs
remDr$navigate('https://stackoverflow.com/')
remDr$executeScript("window.open('https://stackoverflow.com/questions', '_blank');")
# get the handles
handles <- remDr$getWindowHandles()
handles
# switch to second tab and scroll down
remDr$switchToWindow(handles[[2]])
remDr$executeScript("window.scrollTo(0, document.body.scrollHeight);")
# the above doesn't work because current tab is still the first
remDr$getCurrentWindowHandle()
The solution mentioned in the comment here works. Credit goes to @johndharrison who wrote a function myswitch in this post adressing the issue.
library(RSelenium)
# setup connection
rs_driver_object <- rsDriver(browser = "chrome", chromever = "138.0.7204.50",
verbose = T, port = port4me::port4me(), check = T,
phantomver = NULL,
extraCapabilities= list("-sessionTimeout 7200"))
remDr <- rs_driver_object$client
# create two tabs
remDr$navigate('https://stackoverflow.com/')
remDr$executeScript("window.open('https://stackoverflow.com/questions', '_blank');")
# get window handles
handles <- remDr$getWindowHandles()
myswitch <- \(remDr, windowId) {
# use to switch window handle to windowId
# source: https://github.com/ropensci/RSelenium/issues/143#issuecomment-324123029
qpath <- sprintf("%s/session/%s/window", remDr$serverURL, remDr$sessionInfo[["id"]])
remDr$queryRD(qpath, "POST", qdata = list(handle = windowId))
}
# change to window 1 using myswitch
myswitch(remDr, handles[[1]])
# scroll down
remDr$executeScript("window.scrollTo(0, document.body.scrollHeight);")