Implement Page.addScriptToEvaluateOnNewDocument CDP handler (#57248)

Summary:
Pull Request resolved: https://github.com/react/react-native/pull/57248

Implement the CDP `Page.addScriptToEvaluateOnNewDocument` and `Page.removeScriptToEvaluateOnNewDocument` methods in the modern JS inspector (`jsinspector-modern`). `Page.addScriptToEvaluateOnNewDocument` registers a JavaScript snippet that is evaluated in every new JS runtime created for the Host (for example, after a reload), before the application's main bundle runs, matching the standard Chrome DevTools Protocol semantics. This is useful for debugger frontends and tooling that need to install instrumentation ahead of application code.

The registered scripts are stored as session state (alongside `Runtime.addBinding` subscriptions in `SessionState`) and replayed onto each new runtime by `RuntimeAgent` via the runtime executor, so they run before any user code and survive reloads. Per CDP semantics the script does not run in the runtime that is current when it is registered; the client triggers `Page.reload` to apply it. `HostAgent` handles both methods, returning the generated script `identifier` from add and removing by `identifier` on remove.

Changelog:
[General][Added] - Implement the `Page.addScriptToEvaluateOnNewDocument` and `Page.removeScriptToEvaluateOnNewDocument` CDP methods in the modern inspector

Reviewed By: hoxyq

Differential Revision: D107084044

fbshipit-source-id: 7951028f81f89fbf36418cf8da8a03a7191d228a
This commit is contained in:
Gijs Weterings authored and meta-codesync[bot] committed 2026-06-17 08:04:21 -07:00
1 parent 79adce3942
commit bc20ec88eb
15 files changed
+253

No files matched your search

@@ -21,8 +21,10 @@
#include <folly/json.h>
#include <jsinspector-modern/cdp/CdpJson.h>
#include <algorithm>
#include <chrono>
#include <functional>
#include <string>
#include <string_view>
using namespace std::chrono;
@@ -236,6 +238,53 @@ class HostAgent::Impl final {
};
}
}
if (req.method == "Page.addScriptToEvaluateOnNewDocument") {
// @cdp Page.addScriptToEvaluateOnNewDocument registers a script that
// will be evaluated in every new JS runtime created for this Host
// (e.g. after a reload), BEFORE the app's main bundle runs. We store
// it as session state and let each new RuntimeAgent replay it onto its
// runtime, mirroring the handling of @cdp Runtime.addBinding. Per CDP
// semantics the script does NOT run in the runtime that is current
// when it is registered; the client must reload to apply it.
std::string source =
req.params.isObject() && (req.params.count("source") != 0u)
? req.params.at("source").asString()
: std::string();
std::string identifier =
std::to_string(sessionState_.nextScriptToEvaluateOnNewDocumentId++);
sessionState_.scriptsToEvaluateOnNewDocument.push_back(
{.identifier = identifier, .source = std::move(source)});
frontendChannel_(
cdp::jsonResult(
req.id, folly::dynamic::object("identifier", identifier)));
return {
.isFinishedHandlingRequest = true,
.shouldSendOKResponse = false,
};
}
if (req.method == "Page.removeScriptToEvaluateOnNewDocument") {
std::string identifier =
req.params.isObject() && (req.params.count("identifier") != 0u)
? req.params.at("identifier").asString()
: std::string();
auto& scripts = sessionState_.scriptsToEvaluateOnNewDocument;
scripts.erase(
std::remove_if(
scripts.begin(),
scripts.end(),
[&identifier](
const SessionState::ScriptToEvaluateOnNewDocument& script) {
return script.identifier == identifier;
}),
scripts.end());
return {
.isFinishedHandlingRequest = true,
.shouldSendOKResponse = true,
};
}
if (req.method == "Overlay.setPausedInDebuggerMessage") {
auto message =
req.params.isObject() && (req.params.count("message") != 0u)
@@ -397,6 +446,11 @@ class HostAgent::Impl final {
return;
}
if (requestState.isFinishedHandlingRequest) {
// The handler already sent its own response via frontendChannel_.
return;
}
throw NotImplementedException(req.method);
}
@@ -33,6 +33,13 @@ RuntimeAgent::RuntimeAgent(
}
}
// Replay any scripts registered via @cdp
// Page.addScriptToEvaluateOnNewDocument onto this newly created runtime, in
// registration order, so they evaluate before the app's main bundle.
for (const auto& script : sessionState_.scriptsToEvaluateOnNewDocument) {
targetController_.installScriptToEvaluateOnNewDocument(script.source);
}
if (sessionState_.isRuntimeDomainEnabled) {
targetController_.notifyDomainStateChanged(
RuntimeTargetController::Domain::Runtime, true, *this);
@@ -130,6 +130,21 @@ void RuntimeTarget::installBindingHandler(const std::string& bindingName) {
});
}
void RuntimeTarget::installScriptToEvaluateOnNewDocument(
const std::string& source) {
jsExecutor_([source](jsi::Runtime& runtime) {
try {
runtime.evaluateJavaScript(
std::make_shared<jsi::StringBuffer>(source),
"<addScriptToEvaluateOnNewDocument>");
} catch (jsi::JSIException&) {
// Swallow exceptions thrown while evaluating the injected script so a
// faulty script cannot break the app. This mirrors how
// installBindingHandler isolates binding-setup failures.
}
});
}
void RuntimeTarget::installFastRefreshHandler() {
jsExecutor_([selfExecutor = executorFromThis()](jsi::Runtime& runtime) {
auto globalObj = runtime.global();
@@ -313,6 +328,11 @@ void RuntimeTargetController::installBindingHandler(
target_.installBindingHandler(bindingName);
}
void RuntimeTargetController::installScriptToEvaluateOnNewDocument(
const std::string& source) {
target_.installScriptToEvaluateOnNewDocument(source);
}
void RuntimeTargetController::enableSamplingProfiler() {
target_.enableSamplingProfiler();
}
@@ -129,6 +129,14 @@ class RuntimeTargetController {
*/
void installBindingHandler(const std::string &bindingName);
/**
* Evaluates the given JavaScript source on the runtime's thread before any
* user code runs. Used to replay @cdp
* Page.addScriptToEvaluateOnNewDocument scripts onto a freshly created
* runtime.
*/
void installScriptToEvaluateOnNewDocument(const std::string &source);
/**
* Notifies the target that an agent has received an enable or disable
* message for the given domain.
@@ -289,6 +297,14 @@ class JSINSPECTOR_EXPORT RuntimeTarget : public EnableExecutorFromThis<RuntimeTa
*/
void installBindingHandler(const std::string &bindingName);
/**
* Evaluates the given JavaScript source on the runtime's thread before any
* user code runs. Used to replay @cdp
* Page.addScriptToEvaluateOnNewDocument scripts onto a freshly created
* runtime.
*/
void installScriptToEvaluateOnNewDocument(const std::string &source);
/**
* Installs any global values we want to expose to framework/user JavaScript
* code.
@@ -14,6 +14,7 @@
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace facebook::react::jsinspector_modern {
@@ -43,6 +44,36 @@ struct SessionState {
*/
std::unordered_map<std::string, ExecutionContextSelectorSet> subscribedBindings;
/**
* A single script registered during this session using @cdp
* Page.addScriptToEvaluateOnNewDocument.
*/
struct ScriptToEvaluateOnNewDocument {
/** Opaque identifier returned to the frontend, used by @cdp
* Page.removeScriptToEvaluateOnNewDocument. */
std::string identifier;
/** The JavaScript source to evaluate. */
std::string source;
};
/**
* Scripts registered during this session using @cdp
* Page.addScriptToEvaluateOnNewDocument, in registration order.
*
* Like subscribedBindings, these are treated as session state: each new
* RuntimeAgent replays them onto its runtime so they evaluate before any
* user code (i.e. before the app's main bundle). Per CDP semantics they do
* NOT run in the runtime that is current when they are registered - the
* client must trigger a reload (@cdp Page.reload) for them to take effect.
*/
std::vector<ScriptToEvaluateOnNewDocument> scriptsToEvaluateOnNewDocument;
/**
* Monotonic counter for generating the identifiers returned from @cdp
* Page.addScriptToEvaluateOnNewDocument.
*/
unsigned int nextScriptToEvaluateOnNewDocumentId{1};
/**
* Messages logged through the HostAgent::sendConsoleMessage and
* InstanceAgent::sendConsoleMessage utilities that have not yet been sent to
@@ -217,6 +217,59 @@ TEST_F(HostTargetProtocolTest, PageReloadMethod) {
})");
}
TEST_F(HostTargetProtocolTest, PageAddAndRemoveScriptToEvaluateOnNewDocument) {
InSequence s;
// The first registered script gets identifier "1".
EXPECT_CALL(fromPage(), onMessage(JsonEq(R"({
"id": 1,
"result": {"identifier": "1"}
})")))
.RetiresOnSaturation();
toPage_->sendMessage(R"({
"id": 1,
"method": "Page.addScriptToEvaluateOnNewDocument",
"params": {"source": "globalThis.__a = 1;"}
})");
// The second registration gets a distinct, monotonically increasing id "2".
EXPECT_CALL(fromPage(), onMessage(JsonEq(R"({
"id": 2,
"result": {"identifier": "2"}
})")))
.RetiresOnSaturation();
toPage_->sendMessage(R"({
"id": 2,
"method": "Page.addScriptToEvaluateOnNewDocument",
"params": {"source": "globalThis.__b = 2;"}
})");
// Removing a registered script succeeds with an empty result.
EXPECT_CALL(fromPage(), onMessage(JsonEq(R"({
"id": 3,
"result": {}
})")))
.RetiresOnSaturation();
toPage_->sendMessage(R"({
"id": 3,
"method": "Page.removeScriptToEvaluateOnNewDocument",
"params": {"identifier": "1"}
})");
// Removing an unknown identifier is a lenient no-op that still succeeds
// (matching Chrome's behaviour).
EXPECT_CALL(fromPage(), onMessage(JsonEq(R"({
"id": 4,
"result": {}
})")))
.RetiresOnSaturation();
toPage_->sendMessage(R"({
"id": 4,
"method": "Page.removeScriptToEvaluateOnNewDocument",
"params": {"identifier": "999"}
})");
}
TEST_F(HostTargetProtocolTest, OverlaySetPausedInDebuggerMessageMethod) {
InSequence s;
@@ -10860,6 +10860,7 @@ class facebook::react::jsinspector_modern::RuntimeTargetController {
public void emitTracingStateChange(bool isTracing);
public void enableSamplingProfiler();
public void installBindingHandler(const std::string& bindingName);
public void installScriptToEvaluateOnNewDocument(const std::string& source);
public void notifyDomainStateChanged(facebook::react::jsinspector_modern::RuntimeTargetController::Domain domain, bool enabled, const facebook::react::jsinspector_modern::RuntimeAgent& notifyingAgent);
}
@@ -11034,7 +11035,14 @@ struct facebook::react::jsinspector_modern::SessionState {
public bool isRuntimeDomainEnabled;
public facebook::react::jsinspector_modern::RuntimeAgent::ExportedState lastRuntimeAgentExportedState;
public std::unordered_map<std::string, facebook::react::jsinspector_modern::ExecutionContextSelectorSet> subscribedBindings;
public std::vector<facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument> scriptsToEvaluateOnNewDocument;
public std::vector<facebook::react::jsinspector_modern::SimpleConsoleMessage> pendingSimpleConsoleMessages;
public unsigned int nextScriptToEvaluateOnNewDocumentId;
}
struct facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument {
public std::string identifier;
public std::string source;
}
struct facebook::react::jsinspector_modern::SimpleConsoleMessage {
@@ -10486,6 +10486,7 @@ class facebook::react::jsinspector_modern::RuntimeTargetController {
public void emitTracingStateChange(bool isTracing);
public void enableSamplingProfiler();
public void installBindingHandler(const std::string& bindingName);
public void installScriptToEvaluateOnNewDocument(const std::string& source);
public void notifyDomainStateChanged(facebook::react::jsinspector_modern::RuntimeTargetController::Domain domain, bool enabled, const facebook::react::jsinspector_modern::RuntimeAgent& notifyingAgent);
}
@@ -10660,7 +10661,14 @@ struct facebook::react::jsinspector_modern::SessionState {
public bool isRuntimeDomainEnabled;
public facebook::react::jsinspector_modern::RuntimeAgent::ExportedState lastRuntimeAgentExportedState;
public std::unordered_map<std::string, facebook::react::jsinspector_modern::ExecutionContextSelectorSet> subscribedBindings;
public std::vector<facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument> scriptsToEvaluateOnNewDocument;
public std::vector<facebook::react::jsinspector_modern::SimpleConsoleMessage> pendingSimpleConsoleMessages;
public unsigned int nextScriptToEvaluateOnNewDocumentId;
}
struct facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument {
public std::string identifier;
public std::string source;
}
struct facebook::react::jsinspector_modern::SimpleConsoleMessage {
@@ -10713,6 +10713,7 @@ class facebook::react::jsinspector_modern::RuntimeTargetController {
public void emitTracingStateChange(bool isTracing);
public void enableSamplingProfiler();
public void installBindingHandler(const std::string& bindingName);
public void installScriptToEvaluateOnNewDocument(const std::string& source);
public void notifyDomainStateChanged(facebook::react::jsinspector_modern::RuntimeTargetController::Domain domain, bool enabled, const facebook::react::jsinspector_modern::RuntimeAgent& notifyingAgent);
}
@@ -10887,7 +10888,14 @@ struct facebook::react::jsinspector_modern::SessionState {
public bool isRuntimeDomainEnabled;
public facebook::react::jsinspector_modern::RuntimeAgent::ExportedState lastRuntimeAgentExportedState;
public std::unordered_map<std::string, facebook::react::jsinspector_modern::ExecutionContextSelectorSet> subscribedBindings;
public std::vector<facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument> scriptsToEvaluateOnNewDocument;
public std::vector<facebook::react::jsinspector_modern::SimpleConsoleMessage> pendingSimpleConsoleMessages;
public unsigned int nextScriptToEvaluateOnNewDocumentId;
}
struct facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument {
public std::string identifier;
public std::string source;
}
struct facebook::react::jsinspector_modern::SimpleConsoleMessage {
@@ -12702,6 +12702,7 @@ class facebook::react::jsinspector_modern::RuntimeTargetController {
public void emitTracingStateChange(bool isTracing);
public void enableSamplingProfiler();
public void installBindingHandler(const std::string& bindingName);
public void installScriptToEvaluateOnNewDocument(const std::string& source);
public void notifyDomainStateChanged(facebook::react::jsinspector_modern::RuntimeTargetController::Domain domain, bool enabled, const facebook::react::jsinspector_modern::RuntimeAgent& notifyingAgent);
}
@@ -12863,7 +12864,14 @@ struct facebook::react::jsinspector_modern::SessionState {
public bool isRuntimeDomainEnabled;
public facebook::react::jsinspector_modern::RuntimeAgent::ExportedState lastRuntimeAgentExportedState;
public std::unordered_map<std::string, facebook::react::jsinspector_modern::ExecutionContextSelectorSet> subscribedBindings;
public std::vector<facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument> scriptsToEvaluateOnNewDocument;
public std::vector<facebook::react::jsinspector_modern::SimpleConsoleMessage> pendingSimpleConsoleMessages;
public unsigned int nextScriptToEvaluateOnNewDocumentId;
}
struct facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument {
public std::string identifier;
public std::string source;
}
struct facebook::react::jsinspector_modern::SimpleConsoleMessage {
@@ -12390,6 +12390,7 @@ class facebook::react::jsinspector_modern::RuntimeTargetController {
public void emitTracingStateChange(bool isTracing);
public void enableSamplingProfiler();
public void installBindingHandler(const std::string& bindingName);
public void installScriptToEvaluateOnNewDocument(const std::string& source);
public void notifyDomainStateChanged(facebook::react::jsinspector_modern::RuntimeTargetController::Domain domain, bool enabled, const facebook::react::jsinspector_modern::RuntimeAgent& notifyingAgent);
}
@@ -12551,7 +12552,14 @@ struct facebook::react::jsinspector_modern::SessionState {
public bool isRuntimeDomainEnabled;
public facebook::react::jsinspector_modern::RuntimeAgent::ExportedState lastRuntimeAgentExportedState;
public std::unordered_map<std::string, facebook::react::jsinspector_modern::ExecutionContextSelectorSet> subscribedBindings;
public std::vector<facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument> scriptsToEvaluateOnNewDocument;
public std::vector<facebook::react::jsinspector_modern::SimpleConsoleMessage> pendingSimpleConsoleMessages;
public unsigned int nextScriptToEvaluateOnNewDocumentId;
}
struct facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument {
public std::string identifier;
public std::string source;
}
struct facebook::react::jsinspector_modern::SimpleConsoleMessage {
@@ -12565,6 +12565,7 @@ class facebook::react::jsinspector_modern::RuntimeTargetController {
public void emitTracingStateChange(bool isTracing);
public void enableSamplingProfiler();
public void installBindingHandler(const std::string& bindingName);
public void installScriptToEvaluateOnNewDocument(const std::string& source);
public void notifyDomainStateChanged(facebook::react::jsinspector_modern::RuntimeTargetController::Domain domain, bool enabled, const facebook::react::jsinspector_modern::RuntimeAgent& notifyingAgent);
}
@@ -12726,7 +12727,14 @@ struct facebook::react::jsinspector_modern::SessionState {
public bool isRuntimeDomainEnabled;
public facebook::react::jsinspector_modern::RuntimeAgent::ExportedState lastRuntimeAgentExportedState;
public std::unordered_map<std::string, facebook::react::jsinspector_modern::ExecutionContextSelectorSet> subscribedBindings;
public std::vector<facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument> scriptsToEvaluateOnNewDocument;
public std::vector<facebook::react::jsinspector_modern::SimpleConsoleMessage> pendingSimpleConsoleMessages;
public unsigned int nextScriptToEvaluateOnNewDocumentId;
}
struct facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument {
public std::string identifier;
public std::string source;
}
struct facebook::react::jsinspector_modern::SimpleConsoleMessage {
@@ -7864,6 +7864,7 @@ class facebook::react::jsinspector_modern::RuntimeTargetController {
public void emitTracingStateChange(bool isTracing);
public void enableSamplingProfiler();
public void installBindingHandler(const std::string& bindingName);
public void installScriptToEvaluateOnNewDocument(const std::string& source);
public void notifyDomainStateChanged(facebook::react::jsinspector_modern::RuntimeTargetController::Domain domain, bool enabled, const facebook::react::jsinspector_modern::RuntimeAgent& notifyingAgent);
}
@@ -8025,7 +8026,14 @@ struct facebook::react::jsinspector_modern::SessionState {
public bool isRuntimeDomainEnabled;
public facebook::react::jsinspector_modern::RuntimeAgent::ExportedState lastRuntimeAgentExportedState;
public std::unordered_map<std::string, facebook::react::jsinspector_modern::ExecutionContextSelectorSet> subscribedBindings;
public std::vector<facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument> scriptsToEvaluateOnNewDocument;
public std::vector<facebook::react::jsinspector_modern::SimpleConsoleMessage> pendingSimpleConsoleMessages;
public unsigned int nextScriptToEvaluateOnNewDocumentId;
}
struct facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument {
public std::string identifier;
public std::string source;
}
struct facebook::react::jsinspector_modern::SimpleConsoleMessage {
@@ -7692,6 +7692,7 @@ class facebook::react::jsinspector_modern::RuntimeTargetController {
public void emitTracingStateChange(bool isTracing);
public void enableSamplingProfiler();
public void installBindingHandler(const std::string& bindingName);
public void installScriptToEvaluateOnNewDocument(const std::string& source);
public void notifyDomainStateChanged(facebook::react::jsinspector_modern::RuntimeTargetController::Domain domain, bool enabled, const facebook::react::jsinspector_modern::RuntimeAgent& notifyingAgent);
}
@@ -7853,7 +7854,14 @@ struct facebook::react::jsinspector_modern::SessionState {
public bool isRuntimeDomainEnabled;
public facebook::react::jsinspector_modern::RuntimeAgent::ExportedState lastRuntimeAgentExportedState;
public std::unordered_map<std::string, facebook::react::jsinspector_modern::ExecutionContextSelectorSet> subscribedBindings;
public std::vector<facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument> scriptsToEvaluateOnNewDocument;
public std::vector<facebook::react::jsinspector_modern::SimpleConsoleMessage> pendingSimpleConsoleMessages;
public unsigned int nextScriptToEvaluateOnNewDocumentId;
}
struct facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument {
public std::string identifier;
public std::string source;
}
struct facebook::react::jsinspector_modern::SimpleConsoleMessage {
@@ -7855,6 +7855,7 @@ class facebook::react::jsinspector_modern::RuntimeTargetController {
public void emitTracingStateChange(bool isTracing);
public void enableSamplingProfiler();
public void installBindingHandler(const std::string& bindingName);
public void installScriptToEvaluateOnNewDocument(const std::string& source);
public void notifyDomainStateChanged(facebook::react::jsinspector_modern::RuntimeTargetController::Domain domain, bool enabled, const facebook::react::jsinspector_modern::RuntimeAgent& notifyingAgent);
}
@@ -8016,7 +8017,14 @@ struct facebook::react::jsinspector_modern::SessionState {
public bool isRuntimeDomainEnabled;
public facebook::react::jsinspector_modern::RuntimeAgent::ExportedState lastRuntimeAgentExportedState;
public std::unordered_map<std::string, facebook::react::jsinspector_modern::ExecutionContextSelectorSet> subscribedBindings;
public std::vector<facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument> scriptsToEvaluateOnNewDocument;
public std::vector<facebook::react::jsinspector_modern::SimpleConsoleMessage> pendingSimpleConsoleMessages;
public unsigned int nextScriptToEvaluateOnNewDocumentId;
}
struct facebook::react::jsinspector_modern::SessionState::ScriptToEvaluateOnNewDocument {
public std::string identifier;
public std::string source;
}
struct facebook::react::jsinspector_modern::SimpleConsoleMessage {