@@ -147,6 +147,8 @@ public static class Builder
147147 private @ Nullable FirefoxDriverLogLevel logLevel ;
148148 private @ Nullable Boolean logTruncate ;
149149 private @ Nullable File profileRoot ;
150+ private @ Nullable Integer marionettePort ;
151+ private @ Nullable Integer websocketPort ;
150152
151153 @ Override
152154 public int score (Capabilities capabilities ) {
@@ -204,6 +206,31 @@ public GeckoDriverService.Builder withProfileRoot(@Nullable File root) {
204206 return this ;
205207 }
206208
209+ /**
210+ * Configures geckodriver to connect to an existing Firefox instance via the specified
211+ * Marionette port.
212+ *
213+ * @param marionettePort The port where Marionette is listening on the existing Firefox
214+ * instance.
215+ * @return A self reference.
216+ */
217+ public GeckoDriverService .Builder connectToExisting (int marionettePort ) {
218+ this .marionettePort = marionettePort ;
219+ return this ;
220+ }
221+
222+ /**
223+ * Configures the WebSocket port for BiDi. A value of 0 will automatically allocate a free port.
224+ *
225+ * @param websocketPort The port to use for WebSocket communication, or 0 for automatic
226+ * allocation.
227+ * @return A self reference.
228+ */
229+ public GeckoDriverService .Builder withWebSocketPort (@ Nullable Integer websocketPort ) {
230+ this .websocketPort = websocketPort ;
231+ return this ;
232+ }
233+
207234 @ Override
208235 protected void loadSystemProperties () {
209236 parseLogOutput (GECKO_DRIVER_LOG_PROPERTY );
@@ -229,13 +256,27 @@ protected List<String> createArgs() {
229256 List <String > args = new ArrayList <>();
230257 args .add (String .format (Locale .ROOT , "--port=%d" , getPort ()));
231258
232- int wsPort = PortProber .findFreePort ();
233- args .add (String .format ("--websocket-port=%d" , wsPort ));
234-
235- args .add ("--allow-origins" );
236- args .add (String .format ("http://127.0.0.1:%d" , wsPort ));
237- args .add (String .format ("http://localhost:%d" , wsPort ));
238- args .add (String .format ("http://[::1]:%d" , wsPort ));
259+ // Check if marionette port is specified via connectToExisting method
260+ if (marionettePort != null ) {
261+ args .add ("--connect-existing" );
262+ args .add ("--marionette-port" );
263+ args .add (String .valueOf (marionettePort ));
264+ } else {
265+ // Configure websocket port for BiDi communication
266+ if (websocketPort != null ) {
267+ args .add ("--websocket-port" );
268+ args .add (String .valueOf (websocketPort ));
269+
270+ args .add ("--allow-origins" );
271+ args .add (String .format ("http://127.0.0.1:%d" , websocketPort ));
272+ args .add (String .format ("http://localhost:%d" , websocketPort ));
273+ args .add (String .format ("http://[::1]:%d" , websocketPort ));
274+ } else {
275+ // Use 0 to auto-allocate a free port
276+ args .add ("--websocket-port" );
277+ args .add ("0" );
278+ }
279+ }
239280
240281 if (logLevel != null ) {
241282 args .add ("--log" );
0 commit comments