R/cdp.R

Defines functions browser_url browser_session cdp_eval cdp_size cdp_load cdp_open cdp_timer cdp_session browser_cdp wait_js get_page ws_page http_devtools cdp_data ws_open ws_recv read_exact ws_send

Documented in browser_session

# A minimal client of the Chrome DevTools Protocol (CDP) in base R, which is
# enough to print a page to PDF, take a screenshot, or dump the DOM *after* a
# condition on the page becomes true (command-line flags can only guess how long
# to wait). CDP messages are JSON strings sent over a WebSocket; we only need to
# send commands, and find a few fields in the responses with regular expressions,
# so there is no need for a JSON parser.

# send a text message to the server as a single masked frame (the mask is
# required of clients but is meaningless for a local server, so it is fixed
# instead of consuming random numbers from the user's RNG stream)
ws_send = function(con, text) {
  x = charToRaw(enc2utf8(text)); n = length(x)
  len = if (n < 126) as.raw(128 + n) else if (n < 65536) {
    c(as.raw(254), writeBin(as.integer(n), raw(), size = 2, endian = 'big'))
  } else c(as.raw(255), raw(4), writeBin(as.integer(n), raw(), size = 4, endian = 'big'))
  mask = as.raw(c(55, 250, 33, 148))
  writeBin(c(as.raw(129), len, mask, xor(x, rep_len(mask, n))), con)
  flush(con)
}

# read exactly n bytes (readBin() may return fewer on a socket)
read_exact = function(con, n) {
  x = raw()
  while (length(x) < n) {
    y = readBin(con, 'raw', n - length(x))
    if (!length(y)) stop2('The connection to the browser was closed.')
    x = c(x, y)
  }
  x
}

# read a text message, which may consist of multiple frames
ws_recv = function(con) {
  msg = list()
  repeat {
    h = as.integer(read_exact(con, 2))
    op = bitwAnd(h[1], 15); n = bitwAnd(h[2], 127)
    if (n == 126) n = sum(as.integer(read_exact(con, 2)) * 256^(1:0))
    if (n == 127) n = sum(as.integer(read_exact(con, 8)) * 256^(7:0))
    p = read_exact(con, n)  # frames from the server are not masked
    if (op == 8) stop2('The connection to the browser was closed.')
    if (op > 1) next  # ignore ping/pong
    msg[[length(msg) + 1]] = p
    if (bitwAnd(h[1], 128) > 0) break  # the final frame
  }
  raw_to_utf8(do.call(c, msg))
}

# open a WebSocket connection to the DevTools server of the browser
ws_open = function(port, path, timeout) {
  con = local_socket(port, timeout = timeout)
  writeBin(charToRaw(sprintf(paste0(
    'GET %s HTTP/1.1\r\nHost: 127.0.0.1:%d\r\nUpgrade: websocket\r\n',
    'Connection: Upgrade\r\nSec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n'
  ), path, port, base64_encode(as.raw(1:16)))), con)
  # skip the HTTP response headers
  if (is.null(read_headers(con))) stop2('Failed to connect to the browser.')
  con
}

# extract the base64 data from a CDP response and decode it (the data can be
# many MB, so avoid regular expressions on the whole string)
cdp_data = function(x, key = '"data":"') {
  i = regexpr(key, x, fixed = TRUE)
  if (i < 0) stop2('Failed to get the data from the browser.')
  x = substr(x, i + attr(i, 'match.length'), nchar(x))
  j = regexpr('"', x, fixed = TRUE)
  if (j < 0) stop2('Failed to get the data from the browser.')
  base64_decode(substr(x, 1, j - 1))
}

# send a request to the HTTP API of the DevTools server and return the body of
# the response (use a socket instead of url() so that proxy settings do not get
# in the way)
http_devtools = function(port, path, method = 'GET') {
  con = local_socket(port)
  on.exit(close(con))
  writeBin(charToRaw(sprintf(
    '%s %s HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n', method, path
  )), con)
  # the server keeps the connection open, so read the body by Content-Length
  h = read_headers(con)
  if (is.null(h)) return('')
  n = content_length(h)
  gsub('\r?\n', '', raw_to_utf8(read_exact(con, if (is.na(n)) 0L else n)))
}

# the WebSocket path of the first page in the JSON response of the server
ws_page = function(x) {
  r = '"type": *"page"[^}]*"webSocketDebuggerUrl": *"ws://[^/"]+(/[^"]+)"'
  m = regmatches(x, regexec(r, x))[[1]]
  if (length(m) > 1) m[2]
}

# get the WebSocket path of a page; if the browser has not opened one, create it
get_page = function(port, timed_out) {
  for (i in seq_len(1e6)) {
    x = http_devtools(port, '/json/list')
    if (length(path <- ws_page(x))) return(path)
    if (i %% 10 == 0) {
      x = http_devtools(port, '/json/new?about:blank', 'PUT')
      if (length(path <- ws_page(x))) return(path)
    }
    if (timed_out()) stop2(
      'The browser did not open a page. The last response of the browser: ',
      substr(x, 1, 500)
    )
    Sys.sleep(.2)
  }
}

# Turn `wait` into a JavaScript expression: a string is used as is, and a named
# vector/list c(event = , trigger = ) means waiting for an event on `window`
# (after dispatching the `trigger` event to request something, if provided).
wait_js = function(wait) {
  if (is.null(wait)) return('true')
  if (is.null(names(wait))) return(one_string(wait))
  wait = as.list(wait)
  if (!is.character(wait$event) || length(wait$event) != 1) stop2(
    "'wait' must be a JavaScript expression, or a named vector with an 'event' ",
    "(the name of an event to wait for) and optionally a 'trigger' (the name of ",
    "an event to dispatch first)."
  )
  sprintf(
    'new Promise(r => { addEventListener(%s, r, {once: true}); %s })',
    tojson(wait$event),
    if (length(wait$trigger)) sprintf('dispatchEvent(new Event(%s))', tojson(wait$trigger)) else ''
  )
}

# Start the browser with remote debugging, load `url`, wait until the page is
# ready (`wait` is a JavaScript expression), and get the result of `type`: 'pdf',
# 'png', 'jpeg' (raw vector), or 'dom' (the HTML of the page).
browser_cdp = function(...) with_browser_tmp(cdp_session(...))

cdp_session = function(browser, args, url, wait, timeout, size, type) {
  s = cdp_open(browser, args, timeout)
  on.exit(s$close())
  call = s$call
  cdp_size(s, size)
  cdp_load(s, url, wait, timeout)
  switch(
    type,
    pdf = cdp_data(call(
      'Page.printToPDF', '{"printBackground":true,"preferCSSPageSize":true}'
    )),
    png = , jpeg = cdp_data(call(
      'Page.captureScreenshot', sprintf('{"format":"%s"}', type)
    )),
    dom = cdp_eval(s, 'document.documentElement.outerHTML')
  )
}

# a timer that tells if `timeout` seconds have passed since its creation
cdp_timer = function(timeout) {
  t0 = Sys.time()
  function() difftime(Sys.time(), t0, units = 'secs') > timeout
}

# Start the browser with remote debugging and connect to its page. Return a
# list of `call(method, params)` (send a command and return the response),
# and `close()` (close the browser).
cdp_open = function(browser, args, timeout) {
  dir = tempfile('profile'); err = tempfile()
  args = c(
    args, '--remote-debugging-port=0',
    shQuote(paste0('--user-data-dir=', dir)), 'about:blank'
  )
  timed_out = cdp_timer(timeout)
  system2(browser, args, wait = FALSE, stdout = FALSE, stderr = err)
  # the browser tells us the port of the DevTools server in this file
  f = file.path(dir, 'DevToolsActivePort')
  # (reading the file may fail on Windows when the browser is still writing it)
  read_port = function() tryCatch(readLines(f, warn = FALSE), error = function(e) character())
  while (!(file.exists(f) && length(x <- read_port()) >= 2)) {
    if (timed_out()) browser_fail(
      browser, 'Failed to start the browser', err
    )
    Sys.sleep(.1)
  }
  port = as.integer(x[1]); bpath = x[2]
  con = NULL
  shut = function() {
    try(close(con), silent = TRUE)
    # close the whole browser (via its own endpoint) instead of just the page
    try({
      con2 = ws_open(port, bpath, timeout)
      ws_send(con2, '{"id":1,"method":"Browser.close"}')
      close(con2)
    }, silent = TRUE)
    Sys.sleep(.5)  # give the browser time to exit before its profile is deleted
  }
  ok = FALSE
  on.exit(if (!ok) shut())
  con = ws_open(port, get_page(port, timed_out), timeout)
  id = 0
  call = function(method, params = '{}') {
    id <<- id + 1; i = id
    ws_send(con, sprintf('{"id":%d,"method":"%s","params":%s}', i, method, params))
    repeat {
      m = ws_recv(con)
      if (startsWith(m, sprintf('{"id":%d,', i))) break
    }
    if (grepl('^\\{"id":\\d+,"error":', m)) stop2('DevTools error: ', m)
    m
  }
  ok = TRUE
  list(call = call, close = shut)
}

# Navigate to `url` and wait until the page is ready (`wait` is a JavaScript
# expression).
cdp_load = function(s, url, wait, timeout) {
  timed_out = cdp_timer(timeout)
  s$call('Page.navigate', sprintf('{"url":%s}', tojson(url)))
  # `wait` can be a value (ready when it is true) or a promise (ready when it
  # is resolved)
  ready = tojson(sprintf(paste0(
    "(async () => {",
    "if (location.href === 'about:blank' || document.readyState !== 'complete') return false;",
    "const v = (%s); if (typeof v?.then !== 'function') return !!v; await v; return true;",
    "})()"
  ), wait_js(wait)))
  repeat {
    ok = tryCatch(grepl('"value":true', s$call(
      'Runtime.evaluate',
      sprintf('{"expression":%s,"returnByValue":true,"awaitPromise":true}', ready)
    ), fixed = TRUE), error = function(e) FALSE)
    if (ok) break
    if (timed_out()) stop2(
      'The page was not ready in ', timeout, ' seconds. Please check the ',
      "argument 'wait', or increase 'timeout'."
    )
    Sys.sleep(.2)
  }
}

# set the window size (if provided)
cdp_size = function(s, size) {
  if (!is.null(size)) s$call('Emulation.setDeviceMetricsOverride', sprintf(
    '{"width":%d,"height":%d,"deviceScaleFactor":1,"mobile":false}',
    size[1], size[2]
  ))
}

# evaluate JavaScript code on the page and return the value of its last
# statement as a string (indirect eval() allows multiple statements; base64
# avoids unescaping the JSON string)
cdp_eval = function(s, expr) {
  m = s$call('Runtime.evaluate', sprintf('{"expression":%s}', tojson(sprintf(
    'btoa(unescape(encodeURIComponent(String((0, eval)(%s)))))', tojson(expr)
  ))))
  raw_to_utf8(cdp_data(m, '"value":"'))
}

#' A persistent headless browser session
#'
#' Start a headless browser (Chromium/Chrome/Edge) once and reuse it to load
#' pages and evaluate JavaScript on them via the Chrome DevTools Protocol,
#' instead of starting a new browser for every page as [browser_dom()] does.
#' This is much faster for running many checks against different pages.
#' @inheritParams browser_dom
#' @param args Command-line arguments passed to the browser, by default
#'   `xfun:::browser_args()`.
#' @param size The window size, e.g., `c(1280, 1024)`; the browser default if
#'   `NULL`.
#' @return A list of functions: `open(input, query, wait)` loads a page (see
#'   [browser_print()] for the arguments) and returns the session invisibly;
#'   `eval(expr)` evaluates JavaScript code on the current page and returns
#'   the value of its last statement as a string; `dom()` returns the HTML of the current
#'   page; `close()` closes the browser (it is also closed when the session is
#'   garbage-collected or R exits).
#' @export
#' @examplesIf interactive()
#' s = xfun::browser_session()
#' f = tempfile(fileext = ".html")
#' writeLines('<p id="a">hello</p>', f)
#' s$open(f)
#' s$eval('document.getElementById("a").textContent')
#' s$close()
browser_session = function(
  browser = NULL, args = browser_args(), size = NULL, timeout = 60
) {
  browser = check_browser(browser)
  # keep the scratch files of the browser in a directory deleted on close
  d = tempfile('browser-'); dir.create(d)
  old = set_envvar(c(TMPDIR = d))
  s = tryCatch(cdp_open(browser, args, timeout), finally = set_envvar(old), error = function(e) {
    unlink(d, recursive = TRUE, force = TRUE)
    stop(e)
  })
  cdp_size(s, size)
  closed = FALSE
  close = function() {
    if (closed) return(invisible())
    closed <<- TRUE
    s$close()
    unlink(d, recursive = TRUE, force = TRUE)
  }
  self = list(
    open = function(input, query = NULL, wait = NULL) {
      cdp_load(s, browser_url(input, query), wait, timeout)
      invisible(self)
    },
    eval = function(expr) cdp_eval(s, expr),
    dom = function() cdp_eval(s, 'document.documentElement.outerHTML'),
    close = close
  )
  e = environment(close)
  reg.finalizer(e, function(e) close(), onexit = TRUE)
  self
}

# turn a path into a file:// URL and append query parameters (a named list or
# vector) to the URL
browser_url = function(input, query = NULL) {
  if (!grepl('^[a-zA-Z][a-zA-Z0-9+.-]*:(//|[^\\\\/])', input)) {  # not a URL
    input = paste0(
      'file://', if (is_windows()) '/', URLencode(normalize_path(input))
    )
  }
  if (length(query)) {
    q = paste0(
      URLencode(names(query), TRUE), '=',
      URLencode(vapply(query, as.character, ''), TRUE), collapse = '&'
    )
    x = strsplit(input, '#', fixed = TRUE)[[1]]
    input = paste0(
      x[1], if (grepl('?', x[1], fixed = TRUE)) '&' else '?', q,
      if (length(x) > 1) paste0('#', paste(x[-1], collapse = '#'))
    )
  }
  input
}

Try the xfun package in your browser

Any scripts or data that you put into this service are public.

xfun documentation built on Nov. 30, 2026, 9:06 a.m.