| ChromoteSession {chromote} | R Documentation |
ChromoteSession class
Description
This represents one session in a Chromote object. Note that in the Chrome DevTools Protocol a session is a debugging session connected to a target, which is a browser window/tab or an iframe.
A single target can potentially have more than one session connected to it, but this is not currently supported by chromote.
Public fields
parentChromoteobjectdefault_timeoutDefault timeout in seconds for chromote to wait for a Chrome DevTools Protocol response.
protocolDynamic protocol implementation. For expert use only!
Methods
Public methods
Method new()
Create a new ChromoteSession object.
Examples
# 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()
Usage
ChromoteSession$new( parent = default_chromote_object(), width = 992, height = 1323, targetId = NULL, wait_ = TRUE, auto_events = NULL )
Arguments
parentChromoteobject to use; defaults todefault_chromote_object()width, heightWidth and height of the new window.
targetIdTarget ID of an existing target to attach to. When a
targetIdis provided, thewidthandheightarguments are ignored. If NULL (the default) a new target is created and attached to, and thewidthandheightarguments determine its viewport size.wait_If
FALSE, return apromises::promise()of a newChromoteSessionobject. Otherwise, block during initialization, and return aChromoteSessionobject directly.auto_eventsIf
NULL(the default), use theauto_eventssetting from the parentChromoteobject. IfTRUE, enable automatic event enabling/disabling; ifFALSE, disable automatic event enabling/disabling.
Returns
A new ChromoteSession object.
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().
Examples
# Create a new `ChromoteSession` object.
b <- ChromoteSession$new()
# Navigate to page
b$Page$navigate("http://www.r-project.org/")
# View current chromote session
if (interactive()) b$view()
Usage
ChromoteSession$view()
Method close()
Close the Chromote session.
Examples
# Create a new `ChromoteSession` object.
b <- ChromoteSession$new()
# Navigate to page
b$Page$navigate("http://www.r-project.org/")
# Close current chromote session
b$close()
Usage
ChromoteSession$close(wait_ = TRUE)
Arguments
wait_If
FALSE, return apromises::promise()that will resolve when theChromoteSessionis closed. Otherwise, block until theChromoteSessionhas closed.
Method screenshot()
Take a PNG screenshot
Examples
# 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!
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,
options = list(),
wait_ = TRUE
)Arguments
filenameFile path of where to save the screenshot. The format of the screenshot is inferred from the file extension; use
options = list(format = "jpeg")to manually choose the format. SeePage.captureScreenshotfor supported formats; at the time of this release the format options were"png"(default),"jpeg", or"webp".selectorCSS selector to use for the screenshot.
cliprectA list containing
x,y,width, andheight. SeePage.Viewportfor more information. If provided,selectorandexpandwill be ignored. To provide a scale, use thescaleparameter.regionCSS region to use for the screenshot.
expandExtra pixels to expand the screenshot. May be a single value or a numeric vector of top, right, bottom, left values.
scalePage scale factor
showIf
TRUE, the screenshot will be displayed in the viewer.delayThe number of seconds to wait before taking the screenshot after resizing the page. For complicated pages, this may need to be increased.
optionsAdditional options passed to
Page.captureScreenshot.wait_If
FALSE, return apromises::promise()that will resolve when theChromoteSessionhas saved the screenshot. Otherwise, block until theChromoteSessionhas saved the screenshot.
Method screenshot_pdf()
Take a PDF screenshot
Examples
# Create a new `ChromoteSession` object.
b <- ChromoteSession$new()
# Navigate to page
b$Page$navigate("http://www.r-project.org/")
# Take screenshot
tmppdffile <- tempfile(fileext = ".pdf")
b$screenshot_pdf(tmppdffile)
# Show PDF file info
unlist(file.info(tmppdffile))
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
filenameFile path of where to save the screenshot.
pagesizeA single character value in the set
"letter","legal","tabloid","ledger"and"a0"through"a1". Or a numeric vectorc(width, height)specifying the page size.marginsA numeric vector
c(top, right, bottom, left)specifying the page margins.unitsPage and margin size units. Either
"in"or"cm"for inches and centimeters respectively.landscapePaper orientation.
display_header_footerDisplay header and footer.
print_backgroundPrint background graphics.
scalePage scale factor.
wait_If
FALSE, return apromises::promise()that will resolve when theChromoteSessionhas saved the screenshot. Otherwise, block until theChromoteSessionhas saved the screnshot.
Method new_session()
Create a new tab / window
Examples
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/"
Usage
ChromoteSession$new_session( width = 992, height = 1323, targetId = NULL, wait_ = TRUE )
Arguments
width, heightWidth and height of the new window.
targetIdTarget ID of an existing target to attach to. When a
targetIdis provided, thewidthandheightarguments are ignored. If NULL (the default) a new target is created and attached to, and thewidthandheightarguments determine its viewport size.wait_If
FALSE, return apromises::promise()that will resolve when theChromoteSessionhas created a new session. Otherwise, block until theChromoteSessionhas created a new session.
Method get_session_id()
Retrieve the session id
Usage
ChromoteSession$get_session_id()
Method respawn()
Create a new session that connects to the same target (i.e. page) as this session. This is useful if the session has been closed but the target still exists.
Usage
ChromoteSession$respawn()
Method get_target_id()
Retrieve the target id
Usage
ChromoteSession$get_target_id()
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.
Examples
b <- ChromoteSession$new() # Async with promise p <- b$Browser$getVersion(wait_ = FALSE) p$then(str) # Async with callback b$Browser$getVersion(wait_ = FALSE, callback_ = str)
Usage
ChromoteSession$wait_for(p)
Arguments
pA promise to resolve.
Method debug_log()
Send a debug log message to the parent Chromote object
Examples
b <- ChromoteSession$new()
b$parent$debug_messages(TRUE)
b$Page$navigate("https://www.r-project.org/")
#> SEND {"method":"Page.navigate","params":{"url":"https://www.r-project.org/"}| __truncated__}
# Turn off debug messages
b$parent$debug_messages(FALSE)
Usage
ChromoteSession$debug_log(...)
Arguments
...Arguments pasted together with
paste0(..., collapse = "").
Method get_child_loop()
later loop.
For expert async usage only.
Usage
ChromoteSession$get_child_loop()
Method send_command()
Send command through Chrome DevTools Protocol.
For expert use only.
Usage
ChromoteSession$send_command( msg, callback = NULL, error = NULL, timeout = NULL )
Arguments
msgA JSON-serializable list containing
method, andparams.callbackMethod to run when the command finishes successfully.
errorMethod to run if an error occurs.
timeoutNumber of milliseconds for Chrome DevTools Protocol execute a method.
Method get_auto_events()
Resolved auto_events value.
For internal use only.
Usage
ChromoteSession$get_auto_events()
Method invoke_event_callbacks()
Immediately call all event callback methods.
For internal use only.
Usage
ChromoteSession$invoke_event_callbacks(event, params)
Arguments
eventA single event string
paramsA list of parameters to pass to the event callback methods.
Method mark_closed()
Mark a session, and optionally, the underlying target, as closed. For internal use only.
Usage
ChromoteSession$mark_closed(target_closed)
Arguments
target_closedHas the underlying target been closed as well as the active debugging session?
Method is_active()
Retrieve active status
Once initialized, the value returned is TRUE. If $close() has been
called, this value will be FALSE.
Usage
ChromoteSession$is_active()
Method check_active()
Check that a session is active, erroring if not.
Usage
ChromoteSession$check_active()
Method get_init_promise()
Initial promise
For internal use only.
Usage
ChromoteSession$get_init_promise()
Method print()
Summarise the current state of the object.
Usage
ChromoteSession$print(..., verbose = FALSE)
Arguments
...Passed on to
format()whenverbose= TRUEverboseThe print method defaults to a brief summary of the most important debugging info; use
verbose = TRUEtp see the complex R6 object.