From 0c207d347953e4f2ddc5d313cc17faa707b56c7e Mon Sep 17 00:00:00 2001 From: Neil Roberts Date: Tue, 12 May 2026 12:20:36 +0200 Subject: [PATCH] jsuno: Add a parameter to execute() to specify a list of global variables Adds an optional parameter to jsuno::execute to specify a list of global variables to define in the global scope of the running script. The values are references to XInterfaces. Change-Id: I03b7de9fb904f4a172324f0e54c11ff9b0d76134 Reviewed-on: https://gerrit.libreoffice.org/c/core/+/205120 Tested-by: Jenkins Reviewed-by: Neil Roberts --- include/jsuno/jsuno.hxx | 17 ++++++++++++++++- jsuno/source/jsuno.cxx | 6 +++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/include/jsuno/jsuno.hxx b/include/jsuno/jsuno.hxx index 7bcb99b50247..65276d1952a0 100644 --- a/include/jsuno/jsuno.hxx +++ b/include/jsuno/jsuno.hxx @@ -14,13 +14,28 @@ #include #include +#include + +#include +#include + +namespace com::sun::star::uno +{ +class XInterface; +} + namespace jsuno { +typedef std::span>> VariableList; + // @return JSON-stringified result (empty string for a value that JSON.stringify drops: `undefined`, // a function, or a symbol) // +// @param aGlobalVariables A list of variables to define in the global scope in the script. +// // @throws css.script.provider.ScriptExceptionRaisedException -LO_DLLPUBLIC_JSUNO OUString execute(OUString const& script); +LO_DLLPUBLIC_JSUNO OUString execute(OUString const& script, + VariableList aGlobalVariables = VariableList()); } /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/jsuno/source/jsuno.cxx b/jsuno/source/jsuno.cxx index b7e9648a96a8..8b8119269ea8 100644 --- a/jsuno/source/jsuno.cxx +++ b/jsuno/source/jsuno.cxx @@ -2488,7 +2488,7 @@ ExceptionData extractExceptionData(JSContext* ctx, ValueRef const& err) } } -OUString jsuno::execute(OUString const& script) +OUString jsuno::execute(OUString const& script, VariableList aGlobalVariables) { auto const rt = JS_NewRuntime(); JS_SetRuntimeOpaque(rt, new RuntimeData(rt)); @@ -2604,6 +2604,10 @@ OUString jsuno::execute(OUString const& script) JS_SetPropertyStr(ctx, uno, "componentContext", wrapUnoObject(ctx, comphelper::getProcessComponentContext())); JS_SetPropertyStr(ctx, global, "uno", uno.release()); + + for (const auto& rVariable : aGlobalVariables) + JS_SetPropertyStr(ctx, global, rVariable.first, wrapUnoObject(ctx, rVariable.second)); + auto const input = script.toUtf8(); ValueRef const evalRes( ctx, JS_Eval(ctx, input.getStr(), input.getLength(), "", JS_EVAL_TYPE_GLOBAL));