Title: | Exchange Commands Between R and 'JavaScript' |
---|---|
Description: | An 'httpuv' based bridge between R and 'JavaScript'. Provides an easy way to exchange commands and data between a web page and a currently running R session. |
Authors: | Svetlana Ovchinnikova [aut, cre], Simon Anders [aut] |
Maintainer: | Svetlana Ovchinnikova <[email protected]> |
License: | GPL-3 |
Version: | 0.6.0 |
Built: | 2025-02-10 04:14:01 UTC |
Source: | https://github.com/anders-biostat/jrc |
This function adds paths to existing directories to the list of allowed directories,
which can be accessed from the server. To any request for files from outside
of the allowed directories the server will response with 403 Forbidden
error.
rootDirectory
(see openPage
) can always be accessed. By default,
when the app is initialized, current working directory
is added to the list of allowed directories. Further changes
of the working directory will not have any affect on this list or files accessibility.
allowDirectories(dirs = NULL)
allowDirectories(dirs = NULL)
dirs |
Vector of paths to existing directories. Can be absolute paths, or paths relative to
the current working directory. If the specified directory doesn't exist, it will be ignored and a
warning will be produced. If |
This function is a wrapper around allowDirectories
method of class App
.
Absolute paths to all currently allowed directories, if dirs = NULL
.
openPage
(check arguments rootDirectory
and allowedDirectories
).
## Not run: # to run this example an installed web browser is required openPage() # The directories must exist allowDirectories(c("~/directory1", "../anotherDirectory")) dirs <- allowDirectories() closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage() # The directories must exist allowDirectories(c("~/directory1", "../anotherDirectory")) dirs <- allowDirectories() closePage() ## End(Not run)
Adds R function names to the list of functions, that can be called from a web page without manual confirmation on the R side.
allowFunctions(funs = NULL)
allowFunctions(funs = NULL)
funs |
Vector of function names to be added to the list. If |
This function is a wrapper around allowFunctions
method of class App
.
Names of all currently allowed functions if funs = NULL
.
allowVariables
, authorize
, openPage
(check argument
allowedFunctions
), callFunction
.
## Not run: # to run this example an installed web browser is required openPage() allowFunctions(c("myFunction1", "print", "someObject$method")) funs <- allowFunctions() closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage() allowFunctions(c("myFunction1", "print", "someObject$method")) funs <- allowFunctions() closePage() ## End(Not run)
This function adds variable names to the list of variables, that can be modified from a web page without manual confirmation on the R side.
allowVariables(vars = NULL)
allowVariables(vars = NULL)
vars |
Vector of variable names to be added to the list. If |
This function is a wrapper around allowVariables
method of class App
.
Names of all currently allowed variables if vars = NULL
.
allowFunctions
, authorize
, openPage
(check argument
allowedVariables
), sendData
.
## Not run: # to run this example an installed web browser is required openPage() allowVariables(c("myVariable", "anotherOne")) vars <- allowVariables() closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage() allowVariables(c("myVariable", "anotherOne")) vars <- allowVariables() closePage() ## End(Not run)
Object of this class represents the entire jrc-based app. It stores all the active connections, client-specific variables and all the global app settings.
You can create interactive apps by initializing new instances of this class and manage the apps with the methods that are described below. There are no limitations on the number of apps that can run simultaneously in one R session.
A wrapper function is also exported for almost each method (see links in the Methods section). This functions allow
you to gain full control over the app without ever dealing with this class. However, in this case only a single app
can run per R session. Attempt to create a new app (with openPage
function) will force the existing one (if any)
to stop. You can always get the App
object for the currently running app with getPage
function.
new(rootDirectory = NULL, startPage = NULL, onStart = NULL, onClose = NULL,
connectionNumber = Inf, allowedFunctions = c(), allowedVariables = c(), sessionVars = NULL)
Creates a new instance of class App
. Check openPage
man page for information about
arguments.
startServer(port = NULL)
Starts a local server that listens to a given port. If port = NULL
, picks a random available port.
See also openPage
.
stopServer()
Closes all active sessions and stops a running server. See also closePage
.
openPage(useViewer = TRUE, browser = NULL)
Opens a new web page either in a browser, or in the R Studio viewer. If useViewer = FALSE
and browser is not selected,
a default installed browser is used. If browser is specified, useViewer
is ignored. This method returns
a new Session
object, which should correspond to the page that has been just opened. However, if someone would start
a new connection at the moment when openPage
method is called, it may return a wrong session. See also openPage
.
getSession(sessionId = NULL)
Returns a session with the given ID or NULL
if session with this ID doesn't exist. If sessionId = NULL
and there is only one active session, returns it. See also getSession
.
closeSession(sessionId = NULL, inactive = NULL, old = NULL)
Closes WebSocket connection of one or multiple sessions and removes all the related data from the app. For more information on
the arguments, please, check closeSession
man page.
getSessionIds()
Returns IDs of all currently active sessions. See also getSessionIds
.
setEnvironment(envir)
Specifies the outer environment of the app, in which all the messages from the web pages will be evaluated. For more information,
please, check setEnvironment
.
allowFunctions(funs = NULL)
Adds function names to a list of allowed R functions. These functions can be called from a web page without authorization
on the R side. If funs = NULL
, returns a list of all currently allowed functions. For more information,
please, check allowFunctions
.
allowVariables(vars = NULL)
Adds variable names to the list of allowed variables. These variables can be changed from a web page without
authorization on the R side. If vars = NULL
, then returns a vector of names of all currently allowed variables.
For more information, please, check allowVariables
.
allowDirectories(dir = NULL)
Allows app to serve files from an existing directory. Files from the rootDirectory
can always be accessed
by the app. By default, the current working directory is
added to the list of the allowed directories, when the app is initialized. All the subdirectories of the allowed
directories can also be accessed. Attempt to request file from outside allowed directory will produce
403 Forbidden
error. If dirs = NULL
, then returns a vector of names of all currently allowed directories.
Also see allowDirectories
.
startPage(path = NULL)
Sets path to a starting web page of the app. Path can be full, relative to the app's root directory or relative
to the current R working directory. If
path = NULL
, returns current path to the starting page.
rootDirectory(path = NULL)
Sets path to the root directory for the server. Any file, requested by the server, will be looked for in this directory.
Can be a full path or a path relative to the current R working directory. If path = NULL
, returns path to the
current root directory.
setLimits(...)
Sets limits for memory usage, number of simultaneously active connections and amount of messages processed per second.
These settings will apply for each new connection. To change memory usage for an existing session use method setLimits
of class Session
. For information about possible arguments, please, check setLimits
.
getPort()
Returns number of the port which the running server listens to. After the app has been initialized, the port number cannot be changed.
jrc
library allows one to get full control over the currently running R session from
a web page. Therefore for security reasons one should manually authorize function calls,
variable assignments or expression evaluations. All the received messages that are not
processed automatically are given an ID and stored. This function allows a message with the
given ID to be evaluated. It can also show a short description of the message and give user
a choice between running it or discarding.
authorize(sessionId = NULL, messageId = NULL, show = FALSE)
authorize(sessionId = NULL, messageId = NULL, show = FALSE)
sessionId |
ID of the session that received the message. If there is only one active session, this argument becomes optional. |
messageId |
ID of the message to be processed. If the session has only one stored message, this argument becomes optional. |
show |
If |
Expressions has to be always authorized before evaluation. One can specify a list of variables that can be changed automatically and functions that can be called without authorization.
This function is a wrapper around authorize
method of class Session
.
allowFunctions
, allowVariables
, setLimits
, getSessionIds
,
getMessageIds
.
## Not run: # to run this example an installed web browser is required openPage() callFunction("jrc.sendCommand", list("k <<- 10"), wait = 1) allowVariables("x") callFunction("jrc.sendData", list("x", 15), wait = 1) callFunction("jrc.sendData", list("y", 20), wait = 1) msgId <- getMessageIds() authorize(messageId = msgId[1]) #run that to first see some information about the message #authorize(messageId = msgId[2], show = TRUE) closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage() callFunction("jrc.sendCommand", list("k <<- 10"), wait = 1) allowVariables("x") callFunction("jrc.sendData", list("x", 15), wait = 1) callFunction("jrc.sendData", list("y", 20), wait = 1) msgId <- getMessageIds() authorize(messageId = msgId[1]) #run that to first see some information about the message #authorize(messageId = msgId[2], show = TRUE) closePage() ## End(Not run)
Calls a function in a web page by its name. It can also pass a list of arguments for the function and save the returned result to a variable.
callFunction( name, arguments = NULL, assignTo = NULL, wait = 0, sessionId = NULL, thisArg = NULL, ... )
callFunction( name, arguments = NULL, assignTo = NULL, wait = 0, sessionId = NULL, thisArg = NULL, ... )
name |
Name of the function. If the function is a method of some object
its name must contain the full chain of calls (e.g. |
arguments |
List of arguments for the function. Note that in JavaScript arguments must be given in a fixed order, naming is not necessary and will be ignored. |
assignTo |
Name of a variable to which will be assigned the returned value of the called function. |
wait |
If |
sessionId |
An ID of the session to which the function call should be sent. Can also be a vector of multiple
session IDs. If |
thisArg |
JavaScript functions (methods) can belong to some object, which
is referred to as |
... |
further arguments passed to |
JavaScript counterpart is jrc.callFunction(name, arguments, assignTo, package, internal)
.
Its arguments are:
name
Name of an R function. If function name hasn't been previously added to the list
of allowed functions (see allowFunctions
or allowedFunctions
argument of openPage
),
attempt to call it from a web page will require manual authorization on the R side.
arguments
(optional)arguments for the function. This should be an Array (for unnamed arguments) or an Object with argument names as keys (for named arguments).
assignTo
(optional)Name of the variable to which the returned value of the function will be assigned in the R session.
If the variable name hasn't been previously added to the list
of allowed variables (see allowVariables
or allowedVariables
argument of openPage
),
attempt to assign it from a web page will require manual authorization on the R side.
package
(optional)If the function needs to be imported from an installed package, name of this package.
internal
(optional)Whether assignment of the function returned value should happen internally or not. If true
, result will be stored
in the session environment and can be accessed from the outside with getSessionVariable
function. If false
, result will be saved to the outer environment of the app (see setEnvironment
).
By default, uses true
for variables that already exist in the session environment
(see setSessionVariables
or sessionVariables
argument of the openPage
function)
and false
otherwise.
This function is a wrapper
around callFunction
method of class Session
.
authorize
, allowFunctions
, allowVariables
,
setEnvironment
, getSessionIds
.
## Not run: # to run this example an installed web browser is required openPage() callFunction("alert", list("Some alertText")) callFunction("Math.random", assignTo = "randomNumber") sendCommand("alert(randomNumber)") closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage() callFunction("alert", list("Some alertText")) callFunction("Math.random", assignTo = "randomNumber") sendCommand("alert(randomNumber)") closePage() ## End(Not run)
Stops the server and closes all currently opened pages (if any). This function is a
wrapper of stopServer
method of class App
.
closePage()
closePage()
Closes WebSocket connections for the selected client sessions and removes all the related
information from memory. If no arguments are provided and there is only one active session,
closes it. This function is a wrapper around method closeSession
of
class App
.
closeSession(sessionId = NULL, inactive = NULL, old = NULL)
closeSession(sessionId = NULL, inactive = NULL, old = NULL)
sessionId |
IDs of the sessions to close. Can be a vector of multiple IDs. |
inactive |
All sessions that were inactive (didn't receive any messages) for the specified amount of time (in seconds) will be closed. |
old |
All sessions that were opened for at least specified amount of time (in seconds) will be closed. |
## Not run: # to run this example an installed web browser is required start <- Sys.time() openPage() app <- getPage() time <- Sys.time() app$openPage(FALSE) app$openPage(FALSE) print(getSessionIds()) # No sessions will be closed closeSession(old = Sys.time() - start) print(getSessionIds()) # One session (the one that has been opened first) will be closed closeSession(old = Sys.time() - time) print(getSessionIds()) time <- Sys.time() sendCommand("jrc.sendCommand('print(\"Hi!\")')", sessionId = getSessionIds()[1], wait = 3) # this will close all sessions except for the one, that has just send a command to R session closeSession(inactive = Sys.time() - time) # if there is only one active session, sessionId becomes an optional argument closeSession() closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required start <- Sys.time() openPage() app <- getPage() time <- Sys.time() app$openPage(FALSE) app$openPage(FALSE) print(getSessionIds()) # No sessions will be closed closeSession(old = Sys.time() - start) print(getSessionIds()) # One session (the one that has been opened first) will be closed closeSession(old = Sys.time() - time) print(getSessionIds()) time <- Sys.time() sendCommand("jrc.sendCommand('print(\"Hi!\")')", sessionId = getSessionIds()[1], wait = 3) # this will close all sessions except for the one, that has just send a command to R session closeSession(inactive = Sys.time() - time) # if there is only one active session, sessionId becomes an optional argument closeSession() closePage() ## End(Not run)
Returns IDs of all currently stored messages.
getMessageIds(sessionId = NULL, simplify = TRUE)
getMessageIds(sessionId = NULL, simplify = TRUE)
sessionId |
ID of the session for which to return message IDs. Can also be a vector of multiple session IDs.
If |
simplify |
If |
For security reasons, most of the messages that are received
from web pages require manual authorization in the R session with authorize
function. Until that happens,
messages are given randomly generated IDs and are stored in memory.
This function is a wrapper around method getMessageIds
of class Session
.
Either a named list or a vector with message IDs.
jrc
offers two ways to control an interactive app. One is by using methods of classes
App
and Session
. This allows one to have any number of apps within one
R session, but requires some understanding of object oriented programming. Another way is to use
provided wrapper functions that are exported by the package. These functions internally work with
the App
object, which is stored in the package namespace upon initialization with
openPage
function. getPage
returns this object if any.
getPage()
getPage()
Object of class App
or NULL
if there is no active app.
This function returns port number for the running server. By default, a random available port is used. One can also
set a port number as an argument of the openPage
function. The port number can't be changed after the app
was initialized.This function
is a wrapper around method getPort
of the class App
.
getPort()
getPort()
Returns Session
by its ID. This function is a wrapper around method
getSession
of class App
.
getSession(sessionId = NULL)
getSession(sessionId = NULL)
sessionId |
ID of the session. If there is only one active session, this argument becomes optional. |
Object of class Session
.
Returns IDs of all currently active sessions. An ID is a randomly generated combination of 6 letters and
numbers that is assigned to each session upon opening. This function is a wrapper around method getSessionIds
of class App
.
getSessionIds()
getSessionIds()
Vector of session IDs.
This function returns a variable, how it is seen from a session, e.g. for all the received function calls and
commands. It searches for the variable in the session environment first, and then, if variable is not found, checks enclosing
frames of the environment, starting from the outer environment of the app (see setEnvironment
). If the variable
doesn't exist, throws an error.
getSessionVariable(varName, sessionId = NULL)
getSessionVariable(varName, sessionId = NULL)
varName |
Name of the variable to search for. Must be a character. |
sessionId |
ID of the session. If there is only one active session, this argument becomes optional. |
This function
is a wrapper around method sessionVariables
of the class Session
.
Requested variable
## Not run: # to run this example an installed web browser is required f <- function(x) {x * 3} openPage(allowedFunctions = "f", allowedVariables = "k", sessionVars = list(k = 0)) k <- getSessionVariable("k") getPage()$openPage(FALSE) id1 <- getSessionIds()[1] id2 <- getSessionIds()[2] sendCommand("jrc.callFunction('f', [10], 'k')", sessionId = id1, wait = 3) sendCommand("jrc.callFunction('f', [20], 'k')", sessionId = id2, wait = 3) k1 <- getSessionVariable("k", id1) k2 <- getSessionVariable("k", id2) closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required f <- function(x) {x * 3} openPage(allowedFunctions = "f", allowedVariables = "k", sessionVars = list(k = 0)) k <- getSessionVariable("k") getPage()$openPage(FALSE) id1 <- getSessionIds()[1] id2 <- getSessionIds()[2] sendCommand("jrc.callFunction('f', [10], 'k')", sessionId = id1, wait = 3) sendCommand("jrc.callFunction('f', [20], 'k')", sessionId = id2, wait = 3) k1 <- getSessionVariable("k", id1) k2 <- getSessionVariable("k", id2) closePage() ## End(Not run)
When R session is not interactive, messages from the server are not processed automatically. In this case, one needs to
keep this function running.
This function, is a wrapper around run_now
or service
. It runs
the service
in a loop with a specified condition.
listen(time = Inf, activeSessions = NULL, condition = NULL)
listen(time = Inf, activeSessions = NULL, condition = NULL)
time |
Time (in seconds), during which the R session should listen to the server. By default, the function runs until
it is not interrupted ( |
activeSessions |
The function runs, until there is at least one active session in the provided app. If there is only
one active app, this argument can be set to |
condition |
Custom condition. This argument must be a function that returns |
## Not run: # to run this example an installed web browser is required openPage() listen(time = 3) ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage() listen(time = 3) ## End(Not run)
openPage
starts a server and opens a new page with a WebSocket connection between it and the current
R session. After that, messages can be exchanged between R session and the web page to generate content on the
web page and to trigger calculations in R as a response to user activity on the page.
openPage( useViewer = TRUE, rootDirectory = NULL, startPage = NULL, port = NULL, browser = NULL, allowedFunctions = NULL, allowedVariables = NULL, allowedDirectories = getwd(), connectionNumber = Inf, sessionVars = NULL, onStart = NULL, onClose = NULL, onlyServer = FALSE )
openPage( useViewer = TRUE, rootDirectory = NULL, startPage = NULL, port = NULL, browser = NULL, allowedFunctions = NULL, allowedVariables = NULL, allowedDirectories = getwd(), connectionNumber = Inf, sessionVars = NULL, onStart = NULL, onClose = NULL, onlyServer = FALSE )
useViewer |
If |
rootDirectory |
A path to the root directory for the server. Any file, requested by the server
will be searched for in this directory. If |
startPage |
A path to an HTML file that should be used as a starting page of the app.
It can be an absolute path to a local file, or it can be relative to the |
port |
Defines which TCP port the server will listen to. If not defined, random available port
will be used (see |
browser |
A browser in which to open a new web page.
If not defined, default browser will be used. For more information check |
allowedFunctions |
List of functions that can be called from a web page without any additional actions
on the R side. All other functions will require authorization in the current R session before they are called.
This argument should be a vector of R function names. Check |
allowedVariables |
List of variables that can be modified from a web page without any additional actions
on the R side. All other variable reassignments must be confirmed in the current R session.
This argument should be a vector of variable names. Check |
allowedDirectories |
List of directories that can be accessed by the server. This argument should be a vector of
paths (absolute or relative to the current working directory) to existing directories. Check |
connectionNumber |
Maximum number of connections that is allowed to be active simultaneously. |
sessionVars |
Named list of variables, that will be declared for each session, when a new connection is opened.
Any changes to these variables will affect only a certain session. Thus they can be used, for instance, to
store a state of each session. For more information, please, check |
onStart |
A callback function that will be executed, when a new connection is opened. This function gets a single
argument, which is an object of class |
onClose |
A callback function that will be executed, when a connection is closed. This function gets a single
argument, which is an object of class |
onlyServer |
If |
jrc
supports four types of messages:
Commands are pieces of R or JavaScript code that will be evaluated on the receiving side. Note,
that any command from a web page must be authorized in the R session for security reasons. A message
with information about how to do that is printed in the console each time a command is received. For more
information, please, check sendCommand
.
Data is any variable that is sent to or from the R session. It must always come with a
name of the variable to which it should be assigned on the receiving side. For more information, please,
check sendData
.
Function calls can be triggered on each side of the WebSocket connection. Alongside the function name,
one can also send a list of arguments and name of a variable to which the returned value of the function will
be assigned. For more information, please, check callFunction
.
Unlike other types of messages, HTML code can be sent only from the R session to a web page. This code will be added to the body of the page.
openPage
function is a wrapper around several methods of class App
. First, it creates an
instance of this class. Then it starts a server that listens to the given port. And finally, it attempts
to open a new web page. It also stores a new app object in the package namespace, which allows other
wrapper functions to access it.
Object of class App
.
closePage
, setEnvironment
, setLimits
, allowVariables
,
allowFunctions
, setSessionVariables
.
Removes a message from the storage of a session. This function is a wrapper around
method removeMessage
of class Session
.
removeMessage(sessionId = NULL, messageId = NULL)
removeMessage(sessionId = NULL, messageId = NULL)
sessionId |
ID of the session from where to remove a message. If there is only one active session, this argument becomes optional. |
messageId |
ID of the message to remove. If there is only one stored message, this argument becomes optional. |
This function removes variables from the environment of a client session. It allows, for instance, to unmask
a variable with the same name from the outer app environment (see setEnvironment
) for the session
(check the example below). This function
is a wrapper around method sessionVariables
of the class Session
.
removeSessionVariables(varNames, sessionId = NULL)
removeSessionVariables(varNames, sessionId = NULL)
varNames |
Names of variables to remove. |
sessionId |
ID of the session. If there is only one active session, this argument becomes optional. |
## Not run: # to run this example an installed web browser is required openPage(allowedVariables = "k", sessionVars = list(k = 10)) k <- -1 getPage()$openPage(FALSE) id1 <- getSessionIds()[1] id2 <- getSessionIds()[2] removeSessionVariables("k", id1) #this changes global 'k', since the variable is no longer masked sendCommand("jrc.sendData('k', 1)", sessionId = id1, wait = 3) #this doesn't affect global 'k' sendCommand("jrc.sendData('k', 5)", sessionId = id2, wait = 3) local_k <- getSessionVariable("k", id2) closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage(allowedVariables = "k", sessionVars = list(k = 10)) k <- -1 getPage()$openPage(FALSE) id1 <- getSessionIds()[1] id2 <- getSessionIds()[2] removeSessionVariables("k", id1) #this changes global 'k', since the variable is no longer masked sendCommand("jrc.sendData('k', 1)", sessionId = id1, wait = 3) #this doesn't affect global 'k' sendCommand("jrc.sendData('k', 5)", sessionId = id2, wait = 3) local_k <- getSessionVariable("k", id2) closePage() ## End(Not run)
sendCommand
sends JavaScript code through the selected WebSocket connection and evaluates it on the specified
web page. Use JavaScript function jrc.sendCommand
to send R code from the web page
and evaluate it in the current R session. All commands send to R from the server will be evaluated
only after authorization in the currently running R session (see authorize
).
sendCommand(command, sessionId = NULL, wait = 0)
sendCommand(command, sessionId = NULL, wait = 0)
command |
A line (or several lines separated by |
sessionId |
An ID of the session to which the command should be sent. Can also be a vector of multiple session IDs.
If |
wait |
If |
Each opened page gets its own environment, where all the commands are evaluated. Any changes
made with the usual assignment operator <-
will be limited to this page-specific environment. The changes
are still saved, but can be accessed only with getSessionVariable
function. To make changes outside
of the page-specific environment use <<-
instead.
In JavaScript one should use windows.varibleName = "SomeValue"
instead of varibleName = "SomeValue"
, in order to make the variable accessible outside of the
current sendCommand
call.
This function is a wrapper around sendCommand
method of class Session
.
authorize
, sendData
, sendHTML
, callFunction
,
openPage
, getSessionIds
.
## Not run: # to run this example an installed web browser is required k <- 0 openPage() sendCommand(paste0("button = document.createElement('input');", "button.type = 'button';", "button.addEventListener('click', function() {jrc.sendCommand('k <<- k + 1')});", "button.value = '+1';", "document.body.appendChild(button);", collapse = "\n")) closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required k <- 0 openPage() sendCommand(paste0("button = document.createElement('input');", "button.type = 'button';", "button.addEventListener('click', function() {jrc.sendCommand('k <<- k + 1')});", "button.value = '+1';", "document.body.appendChild(button);", collapse = "\n")) closePage() ## End(Not run)
Sends a variable to a web page, where it is saved under a specified name. This function
is a wrapper around sendData
method of class Session
.
sendData( variableName, variable, keepAsVector = FALSE, rowwise = TRUE, sessionId = NULL, wait = 0 )
sendData( variableName, variable, keepAsVector = FALSE, rowwise = TRUE, sessionId = NULL, wait = 0 )
variableName |
Name that the variable will have on the web page. |
variable |
Variable to send. |
keepAsVector |
If |
rowwise |
If |
sessionId |
An ID of the session to which the data should be sent. Can also be a vector of multiple session IDs.
If |
wait |
If |
To send data back from the web page to the current R session one should usejrc.sendData(variableName, variable, internal)
.
Its arguments are:
variableName
Name that the variable will have in the R session. If variable name hasn't been previously added to the list
of allowed variables (see allowVariables
or allowedVariables
argument of the openPage
function), attempt to assign it from a web page will require manual authorization on the R side.
variable
Variable to send.
internal
(optional)Whether this variable should be used only by the session that sent it. If true
, variable will be stored
in the session-specific environment and can be accessed from the outside with getSessionVariable
function. If false
, variable will be saved to the outer environment of the app (see setEnvironment
).
By default, uses true
for variables that already exist in the session specific environment
(see setSessionVariables
or sessionVariables
argument of the openPage
function.)
and false
otherwise.
authorize
, allowVariables
, sendCommand
,
callFunction
, sendHTML
, openPage
, getSessionIds
.
## Not run: # to run this example an installed web browser is required openPage() x <- 1:100 sendData("x", x) sendCommand("console.log(x);") sendCommand("jrc.sendData('x', x.filter(function(e) {return e % 2 == 0}))") closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage() x <- 1:100 sendData("x", x) sendCommand("console.log(x);") sendCommand("jrc.sendData('x', x.filter(function(e) {return e % 2 == 0}))") closePage() ## End(Not run)
Sends a piece of HTML code to a web page and adds it at the end
or the body
element. This function is a wrapper around sendHTML
method of
class Session
.
sendHTML(html = "", sessionId = NULL, wait = 0)
sendHTML(html = "", sessionId = NULL, wait = 0)
html |
HTML code that will be added to the web page. |
sessionId |
An ID of the session to which the HTML should be sent. Can also be a vector of multiple session IDs.
If |
wait |
If |
sendData
, sendCommand
, callFunction
,
openPage
.
## Not run: # to run this example an installed web browser is required openPage(FALSE) sendHTML("Test...") sendHTML("This is <b>bold</b>") sendHTML("<table><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></table>") ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage(FALSE) sendHTML("Test...") sendHTML("This is <b>bold</b>") sendHTML("<table><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></table>") ## End(Not run)
Objects of this class handle all the incoming and outgoing messages for one active connection.
Please, avoid creating instances of this class manually. Each Session
object is created when
a WebSocket is opened and serves as a wrapper around it. A manually created object will not have
a WebSocket connection and thus are not functional.
All sessions are stored within an object of class App
and cannot exist and function without it.
One can manipulate a session directly, using its methods described below, via methods of the corresponding
App
object or the provided wrapper function (links to them can be found in the Methods section).
id
Automatically generated ID for this session. ID is a random combination of 6 letters or numbers. Please, do not change the value of this field.
lastActive
Time of the last received message from the session's WebSocket. The timestamp is generated by the
Sys.time
function.
startTime
Time when this session has been started (generated by the Sys.time
function).
getMessageIds()
Returns IDs of all currently stored messages. ID is a combination of 6 random letters and numbers
generated when the message is stored. See also getMessageIds
.
authorize(messageId = NULL, show = FALSE)
Authorizes evaluation of a message. Check authorize
for more information.
removeMessage(messageId = NULL)
Removes a stored message. This can also be done with the authorize
function (set
show = TRUE
and then select the “Ignore message” option). See also removeMessage
.
sendCommand(command, wait = 0)
Sends a JavaScript command to be evaluated on the web page. Check
sendCommand
for more information.
callFunction(name, arguments = NULL, assignTo = NULL, wait = 0, thisArg = NULL, ...)
Calls an existing JavaScript
function on the web page. Check callFunction
for more information.
sendData(variableName, variable, wait = 0, keepAsVector = FALSE, rowwise = TRUE)
Sends data and assigns it to
a variable on the web page. Check sendData
for more information.
sendHTML(html, wait = 0)
Sends HTML code that will be appended to the web page. Check sendHTML
for
more information.
sessionVariables(vars = NULL, varName = NULL, remove = NULL)
Sets or returns variables that are used (read or modified) only by this session. If both arguments are
NULL
, returns environment for this session. If vars
is a named list, adds this variables to the
session environment. If varName
is a character, returns a variable with this name how it is seen from
the session. If the variable doesn't exist, throws an error. If remove
is a vector of characters, removes
variables with these names from the session environment. One can add variables to the session environment,
get one back and remove variables with a single function call. Check setSessionVariables
,
getSessionVariable
, removeSessionVariables
for more information.
setLimits(limits)
Sets limits for memory usage, number of simultaneously active connections and amount of messages processed per second.
For information about possible arguments, please, check setLimits
. This method accepts all the same arguments,
but they should be supplied in a form of list.
Note, that Session
class has some other public methods that are not mentioned in this list. These methods are
intended to be used only by other functions of jrc
package and therefore are not documented.
Defines the outer environment of the app. Outer environment is a parent for all session environments.
It is used to store variables that are common for all the client sessions. The only way to make changes outside of
the outer environment is to use the global assignment operator <<-
if and only if changes are
made to the variable that does not exist in the outer environment.
setEnvironment(envir)
setEnvironment(envir)
envir |
Environment to be used as outer environment. |
By default, an environment where app was initialized (via openPage
function or with App$new()
call)
is used.
This function is a wrapper around setEnvironment
method of class App
.
## Not run: # to run this example an installed web browser is required openPage() e <- new.env() setEnvironment(e) sendCommand("jrc.sendData('x', 10)", wait = 3) print(e$x) closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage() e <- new.env() setEnvironment(e) sendCommand("jrc.sendData('x', 10)", wait = 3) print(e$x) closePage() ## End(Not run)
This function allows to control memory usage and limit number of messages processed per second or simultaneously active connections to the app.
If an app is deployed on a server and is publicly available, it may be useful to limit resources that are available to each user. There are various things that can be controlled by this function: storage size and number of stored messages, maximal variable size, number of messages processed per second and bytes received per second.
Messages are all the communication received via web socket from an opened web page. Each message contains a command that is to be evaluated in the R session, name of a function to call or variable to store. If number or size of messages exceeds the preset limit, they are completely ignored by the app.
setLimits( maxCon = NULL, storageSize = NULL, storedMsg = NULL, varSize = NULL, msgPerSec = NULL, msgSize = NULL, bytesPerSec = NULL )
setLimits( maxCon = NULL, storageSize = NULL, storedMsg = NULL, varSize = NULL, msgPerSec = NULL, msgSize = NULL, bytesPerSec = NULL )
maxCon |
Maximal allowed number of web socket connections simultaneously. A new
connection is established whenever someone requests an HTML page from the server
or when the |
storageSize |
Maximal total size of all stored messages in bytes. |
storedMsg |
Maximal number of messages that can be stored simultaneously. |
varSize |
Maximal size of a variable that can be received from a web page. Attempt to assign data of larger size to a variable will be ignored. |
msgPerSec |
Maximal number of messages that can be received per second. All extra messages will be disposed of immediately without any attempt to process their content. |
msgSize |
Maximal allowed size of a message in bytes. Note, that here a size of character string that contains all the received information is estimated. All larger messages will be ignored. |
bytesPerSec |
Number of bytes that can be received per second. After the limit is reached, all the incoming messages will be ignored. |
For security reasons, some messages has to be first authorized by the
authorize
function, before they can be processed. Such messages
are saved until they are manually removed or authorized. If number or total
size of the stored messages exceeds the limits, new messages are still saved,
but the older ones are removed from the memory. If storage size is set to zero
no messages can be stored and every message that requires authorization will
be automatically discarded.
Size of variables or messages is estimated in object.size
and is always measured in byte.
The limits are set for the entire app and are applied for each new connection.
One can also change security limits for any connection separately by using
method setLimits
of a corresponding object of class Session
.
This function is a wrapper for method setLimits
of class App
.
authorize
, allowFunctions
, allowVariables
.
## Not run: # to run this example an installed web browser is required openPage() setLimits(maxCon = 10) setLimits(varSize = 10 * 1024^2) closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage() setLimits(maxCon = 10) setLimits(varSize = 10 * 1024^2) closePage() ## End(Not run)
Each client session in jrc
, gets its own environment that can be accessed only by this
session (or from the outside with the getSessionVariable
function). General purpose
of these environments is to store some session-specific information such as state of the app for
each user. It can also be used to mask variables from the user: if there are two variables with the
same name in the session environment and outside of it, user will not be able to see the latter one.
This function adds new variables to a session environment or changes values of some existing ones.
setSessionVariables(vars, sessionId = NULL, makeDefault = FALSE)
setSessionVariables(vars, sessionId = NULL, makeDefault = FALSE)
vars |
Named list of variables to be added to a session environment. Names are required and will be used as variable names. |
sessionId |
ID of the session to which variables should be added. Can also be a vector of
multiple session IDs. If |
makeDefault |
If |
This function is a wrapper around method sessionVariables
of class Session
.
If makeDefault = TRUE
, it is also a wrapper around method sessionVariables
of class
App
. The first one changes the current state of the session environment, while the
second specifies default variables for each new session.
## Not run: # to run this example an installed web browser is required openPage(allowedFunctions = "f", allowedVariables = "res") m <- 1 f <- function() {v * m} setSessionVariables(list(v = 1:10, m = 2)) sendCommand("jrc.callFunction('f', [], 'res')", wait = 1) print(res) closePage() ## End(Not run)
## Not run: # to run this example an installed web browser is required openPage(allowedFunctions = "f", allowedVariables = "res") m <- 1 f <- function() {v * m} setSessionVariables(list(v = 1:10, m = 2)) sendCommand("jrc.callFunction('f', [], 'res')", wait = 1) print(res) closePage() ## End(Not run)