Playwright Java over CDP: Set a Proxy on a New Browser Context
Connect to a Chromium CDP endpoint, then create a proxy-configured context; keep the control connection and remote browser’s outbound route distinct.
A remote browser has two network paths: Java's control connection to the browser service, and the browser's requests to websites. Configure the latter on the context you create.
For a Chromium service exposing a CDP endpoint and allowing new contexts:
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.Proxy;
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().connectOverCDP(cdpEndpoint);
try {
var options = new Browser.NewContextOptions().setProxy(
new Proxy("http://proxy.example:8080")
.setUsername(proxyUser)
.setPassword(proxyPassword));
try (BrowserContext context = browser.newContext(options)) {
context.newPage().navigate("https://www.example.org/");
}
} finally {
browser.close();
}
}
cdpEndpoint is the current endpoint supplied by the browser service. Its authentication token and protocol are independent of the forward proxy account.
CDP connections are Chromium-only. A Playwright-protocol endpoint uses connect instead; changing a URL suffix without checking the service's protocol is not a reliable conversion.
The proxy must be reachable from the remote browser's host. A loopback listener on the Java machine is not automatically available there. The new context's setting also does not reconfigure an already existing default context or Java's WebSocket connection.