ChromoteSession class
ChromoteSession class
Public fields
parent
Chromote
objectdefault_timeout
Default timeout in seconds for chromote to wait for a Chrome DevTools Protocol response.
protocol
Dynamic protocol implementation. For expert use only!
Methods
Method new()
Create a new ChromoteSession
object.
Usage
ChromoteSession$new(
parent = default_chromote_object(),
width = 992,
height = 1323,
targetId = NULL,
wait_ = TRUE,
auto_events = NULL
)
Arguments
parent
Chromote
object to use; defaults todefault_chromote_object()
width
Width, in pixels, of the
Target
to create iftargetId
isNULL
height
Height, in pixels, of the
Target
to create iftargetId
isNULL
targetId
Target ID of an existing target to attach to. When a
targetId
is provided, thewidth
andheight
arguments are ignored. If NULL (the default) a new target is created and attached to, and thewidth
andheight
arguments determine its viewport size.wait_
If
FALSE
, return apromises::promise()
of a newChromoteSession
object. Otherwise, block during initialization, and return aChromoteSession
object directly.auto_events
If
NULL
(the default), use theauto_events
setting from the parentChromote
object. IfTRUE
, enable automatic event enabling/disabling; ifFALSE
, disable automatic event enabling/disabling.
Examples
\dontrun{# Create a new `ChromoteSession` object.
b <- ChromoteSession$new()
# Create a ChromoteSession with a specific height,width
b <- ChromoteSession$new(height = 1080, width = 1920)
# Navigate to page
b$Page$navigate("http://www.r-project.org/")
# View current chromote session
if (interactive()) b$view()}
Method view()
Display the current session in the Chromote
browser.
If a Chrome
browser is being used, this method will open a new tab
using your Chrome
browser. When not using a Chrome
browser, set
options(browser=)
to change the default behavior of browseURL()
.
Method close()
Close the Chromote session.
Arguments
wait_
If
FALSE
, return apromises::promise()
that will resolve when theChromoteSession
is closed. Otherwise, block until theChromoteSession
has closed.
Method screenshot()
Take a PNG screenshot
Usage
ChromoteSession$screenshot(
filename = "screenshot.png",
selector = "html",
cliprect = NULL,
region = c("content", "padding", "border", "margin"),
expand = NULL,
scale = 1,
show = FALSE,
delay = 0.5,
wait_ = TRUE
)
Arguments
filename
File path of where to save the screenshot.
selector
CSS selector to use for the screenshot.
cliprect
A list containing
x
,y
,width
, andheight
. SeePage.Viewport
for more information. If provided,selector
andexpand
will be ignored. To provide a scale, use thescale
parameter.region
CSS region to use for the screenshot.
expand
Extra pixels to expand the screenshot. May be a single value or a numeric vector of top, right, bottom, left values.
scale
Page scale factor
show
If
TRUE
, the screenshot will be displayed in the viewer.delay
The number of seconds to wait before taking the screenshot after resizing the page. For complicated pages, this may need to be increased.
wait_
If
FALSE
, return apromises::promise()
that will resolve when theChromoteSession
has saved the screenshot. Otherwise, block until theChromoteSession
has saved the screenshot.
Examples
\dontrun{# Create a new `ChromoteSession` object.
b <- ChromoteSession$new()
# Navigate to page
b$Page$navigate("http://www.r-project.org/")
# Take screenshot
tmppngfile <- tempfile(fileext = ".png")
is_interactive <- interactive() # Display screenshot if interactive
b$screenshot(tmppngfile, show = is_interactive)
# Show screenshot file info
unlist(file.info(tmppngfile))
# Take screenshot using a selector
sidebar_file <- tempfile(fileext = ".png")
b$screenshot(sidebar_file, selector = ".sidebar", show = is_interactive)
# ----------------------------
# Take screenshots in parallel
urls <- c(
"https://www.r-project.org/",
"https://github.com/",
"https://news.ycombinator.com/"
)
# Helper method that:
# 1. Navigates to the given URL
# 2. Waits for the page loaded event to fire
# 3. Takes a screenshot
# 4. Prints a message
# 5. Close the ChromoteSession
screenshot_p <- function(url, filename = NULL) {
if (is.null(filename)) {
filename <- gsub("^.*://", "", url)
filename <- gsub("/", "_", filename)
filename <- gsub("\\.", "_", filename)
filename <- sub("_$", "", filename)
filename <- paste0(filename, ".png")
}
b2 <- b$new_session()
b2$Page$navigate(url, wait_ = FALSE)
b2$Page$loadEventFired(wait_ = FALSE)$
then(function(value) {
b2$screenshot(filename, wait_ = FALSE)
})$
then(function(value) {
message(filename)
})$
finally(function() {
b2$close()
})
}
# Take multiple screenshots simultaneously
ps <- lapply(urls, screenshot_p)
pa <- promises::promise_all(.list = ps)$then(function(value) {
message("Done!")
})
# Block the console until the screenshots finish (optional)
b$wait_for(pa)
#> www_r-project_org.png
#> github_com.png
#> news_ycombinator_com.png
#> Done!}
Method screenshot_pdf()
Take a PDF screenshot
Usage
ChromoteSession$screenshot_pdf(
filename = "screenshot.pdf",
pagesize = "letter",
margins = 0.5,
units = c("in", "cm"),
landscape = FALSE,
display_header_footer = FALSE,
print_background = FALSE,
scale = 1,
wait_ = TRUE
)
Arguments
filename
File path of where to save the screenshot.
pagesize
A single character value in the set
"letter"
,"legal"
,"tabloid"
,"ledger"
and"a0"
through"a1"
. Or a numeric vectorc(width, height)
specifying the page size.margins
A numeric vector
c(top, right, bottom, left)
specifying the page margins.units
Page and margin size units. Either
"in"
or"cm"
for inches and centimeters respectively.landscape
Paper orientation.
display_header_footer
Display header and footer.
print_background
Print background graphics.
scale
Page scale factor.
wait_
If
FALSE
, return apromises::promise()
that will resolve when theChromoteSession
has saved the screenshot. Otherwise, block until theChromoteSession
has saved the screnshot.
Method new_session()
Create a new tab / window
Arguments
width, height
Width and height of the new window.
targetId
Target ID of an existing target to attach to. When a
targetId
is provided, thewidth
andheight
arguments are ignored. If NULL (the default) a new target is created and attached to, and thewidth
andheight
arguments determine its viewport size.wait_
If
FALSE
, return apromises::promise()
that will resolve when theChromoteSession
has created a new session. Otherwise, block until theChromoteSession
has created a new session.
Examples
\dontrun{b1 <- ChromoteSession$new()
b1$Page$navigate("http://www.google.com")
b2 <- b1$new_session()
b2$Page$navigate("http://www.r-project.org/")
b1$Runtime$evaluate("window.location", returnByValue = TRUE)$result$value$href
#> [1] "https://www.google.com/"
b2$Runtime$evaluate("window.location", returnByValue = TRUE)$result$value$href
#> [1] "https://www.r-project.org/"}
Method wait_for()
Wait for a Chromote Session to finish. This method will block the R
session until the provided promise resolves. The loop from
$get_child_loop()
will only advance just far enough for the promise to
resolve.
Method debug_log()
Send a debug log message to the parent Chromote object
Method is_active()
Retrieve active status
Once initialized, the value returned is TRUE
. If $close()
has been
called, this value will be FALSE
.
Examples
## ------------------------------------------------
## Method `ChromoteSession$new`
## ------------------------------------------------
if (FALSE) # Create a new `ChromoteSession` object.
b <- ChromoteSession$new()
# Create a ChromoteSession with a specific height,width
b <- ChromoteSession$new(height = 1080, width = 1920)
# Navigate to page
b$Page$navigate("http://www.r-project.org/")
#> $frameId
#> [1] "E2F5E76113BBDD7B2BB0E7ABEF03ADF2"
#>
#> $loaderId
#> [1] "1D4C2BF02AC59DE1AE973C16E5B384E4"
#>
# View current chromote session
if (interactive()) b$view()
## ------------------------------------------------
## Method `ChromoteSession$view`
## ------------------------------------------------
if (FALSE) # Create a new `ChromoteSession` object.
b <- ChromoteSession$new()
# Navigate to page
b$Page$navigate("http://www.r-project.org/")
#> $frameId
#> [1] "E2F5E76113BBDD7B2BB0E7ABEF03ADF2"
#>
#> $loaderId
#> [1] "7B2E203B1675F55E970631A51A3D417B"
#>
# View current chromote session
if (interactive()) b$view()
## ------------------------------------------------
## Method `ChromoteSession$close`
## ------------------------------------------------
if (FALSE) # Create a new `ChromoteSession` object.
b <- ChromoteSession$new()
# Navigate to page
b$Page$navigate("http://www.r-project.org/")
#> $frameId
#> [1] "E2F5E76113BBDD7B2BB0E7ABEF03ADF2"
#>
#> $loaderId
#> [1] "6C68606782C7E786A1238FE12AE3E9AD"
#>
# Close current chromote session
b$close()
#> [1] TRUE
## ------------------------------------------------
## Method `ChromoteSession$screenshot`
## ------------------------------------------------
if (FALSE) # Create a new `ChromoteSession` object.
b <- ChromoteSession$new()
# Navigate to page
b$Page$navigate("http://www.r-project.org/")
#> Error in self$send_command(msg, callback = callback_, error = error_, timeout = timeout_): Session 398DBEC869667CE0EF0692612A8E6CE0 is closed.
# Take screenshot
tmppngfile <- tempfile(fileext = ".png")
is_interactive <- interactive() # Display screenshot if interactive
b$screenshot(tmppngfile, show = is_interactive)
#> Error in self$send_command(msg, callback = callback_, error = error_, timeout = timeout_): Session 398DBEC869667CE0EF0692612A8E6CE0 is closed.
# Show screenshot file info
unlist(file.info(tmppngfile))
#> size isdir mode mtime ctime atime uid gid uname grname
#> NA NA NA NA NA NA NA NA NA NA
# Take screenshot using a selector
sidebar_file <- tempfile(fileext = ".png")
b$screenshot(sidebar_file, selector = ".sidebar", show = is_interactive)
#> Error in self$send_command(msg, callback = callback_, error = error_, timeout = timeout_): Session 398DBEC869667CE0EF0692612A8E6CE0 is closed.
# ----------------------------
# Take screenshots in parallel
urls <- c(
"https://www.r-project.org/",
"https://github.com/",
"https://news.ycombinator.com/"
)
# Helper method that:
# 1. Navigates to the given URL
# 2. Waits for the page loaded event to fire
# 3. Takes a screenshot
# 4. Prints a message
# 5. Close the ChromoteSession
screenshot_p <- function(url, filename = NULL) {
if (is.null(filename)) {
filename <- gsub("^.*://", "", url)
filename <- gsub("/", "_", filename)
filename <- gsub("\\.", "_", filename)
filename <- sub("_$", "", filename)
filename <- paste0(filename, ".png")
}
b2 <- b$new_session()
b2$Page$navigate(url, wait_ = FALSE)
b2$Page$loadEventFired(wait_ = FALSE)$
then(function(value) {
b2$screenshot(filename, wait_ = FALSE)
})$
then(function(value) {
message(filename)
})$
finally(function() {
b2$close()
})
}
# Take multiple screenshots simultaneously
ps <- lapply(urls, screenshot_p)
pa <- promises::promise_all(.list = ps)$then(function(value) {
message("Done!")
})
# Block the console until the screenshots finish (optional)
b$wait_for(pa)
#> NULL
#> www_r-project_org.png
#> github_com.png
#> news_ycombinator_com.png
#> Done!
## ------------------------------------------------
## Method `ChromoteSession$screenshot_pdf`
## ------------------------------------------------
if (FALSE) # Create a new `ChromoteSession` object.
b <- ChromoteSession$new()
# Navigate to page
b$Page$navigate("http://www.r-project.org/")
#> Error in self$send_command(msg, callback = callback_, error = error_, timeout = timeout_): Session 398DBEC869667CE0EF0692612A8E6CE0 is closed.
# Take screenshot
tmppdffile <- tempfile(fileext = ".pdf")
b$screenshot_pdf(tmppdffile)
#> Error in self$send_command(msg, callback = callback_, error = error_, timeout = timeout_): Session 398DBEC869667CE0EF0692612A8E6CE0 is closed.
# Show PDF file info
unlist(file.info(tmppdffile))
#> size isdir mode mtime ctime atime uid gid uname grname
#> NA NA NA NA NA NA NA NA NA NA
## ------------------------------------------------
## Method `ChromoteSession$new_session`
## ------------------------------------------------
if (FALSE) b1 <- ChromoteSession$new()
b1$Page$navigate("http://www.google.com")
#> Error in eval(expr, envir, enclos): object 'b1' not found
b2 <- b1$new_session()
#> Error in eval(expr, envir, enclos): object 'b1' not found
b2$Page$navigate("http://www.r-project.org/")
#> Error in eval(expr, envir, enclos): object 'b2' not found
b1$Runtime$evaluate("window.location", returnByValue = TRUE)$result$value$href
#> Error in eval(expr, envir, enclos): object 'b1' not found
#> [1] "https://www.google.com/"
b2$Runtime$evaluate("window.location", returnByValue = TRUE)$result$value$href
#> Error in eval(expr, envir, enclos): object 'b2' not found
#> [1] "https://www.r-project.org/"
## ------------------------------------------------
## Method `ChromoteSession$get_session_id`
## ------------------------------------------------
if (FALSE) b <- ChromoteSession$new()
b$get_session_id()
#> [1] "398DBEC869667CE0EF0692612A8E6CE0"
#> [1] "05764F1D439F4292497A21C6526575DA"
## ------------------------------------------------
## Method `ChromoteSession$wait_for`
## ------------------------------------------------
if (FALSE) b <- ChromoteSession$new()
# Async with promise
p <- b$Browser$getVersion(wait_ = FALSE)
#> Error in self$send_command(msg, callback = callback_, error = error_, timeout = timeout_): Session 398DBEC869667CE0EF0692612A8E6CE0 is closed.
p$then(str)
#> Error in eval(expr, envir, enclos): object 'p' not found
# Async with callback
b$Browser$getVersion(wait_ = FALSE, callback_ = str)
#> Error in self$send_command(msg, callback = callback_, error = error_, timeout = timeout_): Session 398DBEC869667CE0EF0692612A8E6CE0 is closed.
## ------------------------------------------------
## Method `ChromoteSession$debug_log`
## ------------------------------------------------
if (FALSE) b <- ChromoteSession$new()
b$parent$debug_messages(TRUE)
b$Page$navigate("https://www.r-project.org/")
#> Error in self$send_command(msg, callback = callback_, error = error_, timeout = timeout_): Session 398DBEC869667CE0EF0692612A8E6CE0 is closed.
#> SEND {"method":"Page.navigate","params":{"url":"https://www.r-project.org/"}| __truncated__}
# Turn off debug messages
b$parent$debug_messages(FALSE)