This tutorial explains you how you can open and close multiple tabs in browser via R. This is useful when you need to do some automation which requires opening URL and refreshing the web page and getting content from it. I use it for refreshing GOOGLEFINANCE( ) TODAY( ) NOW() formulas in google sheets so that I can pull real time stock prices.
The below R function allows flexibility around built-in browseURL( ) function. It supports the following arguments –
URL Specify URL which you want to visit in browser. You can also pass multiple URLs in a character vector.browserName By default it is blank which means URL to be opened in your default browser. Incase you want to open it in a specific browser, you can pass Chrome or Edgeclose If you want to close the tab which you opened. By default it is disabled. You can enable it by passing close = TSleep How many seconds you want to wait before closing the active tab
Make sure to install and load winsendkeys R package before using the below user defined function.
remotes::install_github(“miraisolutions/winsendkeys”)
browserFun browserName = NULL,
Sleep = 20,
close = F) {
if (is.null(browserName) && close) {
stop(“Browser name is required when close = TRUE”)
}
# Path of Google Chrome / MS Edge
if (is.null(browserName)) {
browser = getOption(“browser”)
} else if(tolower(browserName) == “chrome”) {
browser = “C:\Program Files (x86)\Google\Chrome\Application\chrome.exe”
} else if (tolower(browserName) == “edge”) {
browser = “C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe”
}
# Open URL
if(length(URL) > 1) {
lapply(URL,function(x) browseURL(as.character(x), browser = browser))
} else {
browseURL(URL, browser = browser)
}
# Close URL
if(close) {
Sys.sleep(Sleep)
# Send Keys
if(tolower(browserName) == “chrome”) {
winsendkeys::activateWindow(“Chrome”)
} else if (tolower(browserName) == “edge”) {
winsendkeys::activateWindow(“Edge”)
}
if(length(URL) > 1) {
winsendkeys::sendKeys(“{DELAY=100}%{F4}”)
} else {
winsendkeys::sendKeys(“{DELAY=50}^w”)
}
}
NULL
}
browserFun(URL = ‘https://google.com’)
Multiple URLs will be shown in multiple tabs in the browser.
URL = c(‘https://google.com’, ‘https://yahoo.com’)
browserFun(URL = URL)
browserFun(URL = ‘https://google.com’, browserName = “Chrome”)
For Microsoft Edge, you can use browserName = “Edge”
browserFun(URL = ‘https://google.com’, browserName = “Edge”, Sleep = 5, close = T)
URL = c(‘https://google.com’, ‘https://yahoo.com’)
browserFun(URL = URL, browserName = “Edge”, Sleep = 15, close = T)
Location of executable files (.exe) of chrome or edge could be different in your system. If that is the case you need to change the below file location in the function. You can also add other browsers like Firefox or Safari.
“C:\Program Files (x86)\Google\Chrome\Application\chrome.exe”
“C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe”
Read MoreListenData