Class BrowserContextImpl

All Implemented Interfaces:
BrowserContext, AutoCloseable

class BrowserContextImpl extends ChannelOwner implements BrowserContext
  • Field Details

  • Constructor Details

    • BrowserContextImpl

      BrowserContextImpl(ChannelOwner parent, String type, String guid, com.google.gson.JsonObject initializer)
  • Method Details

    • eventSubscriptions

      private static final Map<BrowserContextImpl.EventType,String> eventSubscriptions()
    • setRecordHar

      void setRecordHar(Path path, HarContentPolicy policy)
    • setBaseUrl

      void setBaseUrl(String spec)
    • onClose

      public void onClose(Consumer<BrowserContext> handler)
      Description copied from interface: BrowserContext
      Emitted when Browser context gets closed. This might happen because of one of the following:
      • Browser context is closed.
      • Browser application is closed or crashed.
      • The Browser.close() method was called.
      Specified by:
      onClose in interface BrowserContext
    • offClose

      public void offClose(Consumer<BrowserContext> handler)
      Description copied from interface: BrowserContext
      Removes handler that was previously added with onClose(handler).
      Specified by:
      offClose in interface BrowserContext
    • onConsoleMessage

      public void onConsoleMessage(Consumer<ConsoleMessage> handler)
      Description copied from interface: BrowserContext
      Emitted when JavaScript within the page calls one of console API methods, e.g. console.log or console.dir. Also emitted if the page throws an error or a warning.

      The arguments passed into console.log and the page are available on the ConsoleMessage event handler argument.

      **Usage**

      
       context.onConsoleMessage(msg -> {
         for (int i = 0; i < msg.args().size(); ++i)
           System.out.println(i + ": " + msg.args().get(i).jsonValue());
       });
       page.evaluate("() => console.log('hello', 5, { foo: 'bar' })");
       
      Specified by:
      onConsoleMessage in interface BrowserContext
    • offConsoleMessage

      public void offConsoleMessage(Consumer<ConsoleMessage> handler)
      Description copied from interface: BrowserContext
      Removes handler that was previously added with onConsoleMessage(handler).
      Specified by:
      offConsoleMessage in interface BrowserContext
    • onDialog

      public void onDialog(Consumer<Dialog> handler)
      Description copied from interface: BrowserContext
      Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload. Listener **must** either Dialog.accept() or Dialog.dismiss() the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.

      **Usage**

      
       context.onDialog(dialog -> {
         dialog.accept();
       });
       

      NOTE: When no Page.onDialog() or BrowserContext.onDialog() listeners are present, all dialogs are automatically dismissed.

      Specified by:
      onDialog in interface BrowserContext
    • offDialog

      public void offDialog(Consumer<Dialog> handler)
      Description copied from interface: BrowserContext
      Removes handler that was previously added with onDialog(handler).
      Specified by:
      offDialog in interface BrowserContext
    • onPage

      public void onPage(Consumer<Page> handler)
      Description copied from interface: BrowserContext
      The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will also fire for popup pages. See also Page.onPopup() to receive events about popups relevant to a specific page.

      The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with window.open('http://example.com'), this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup.

      
       Page newPage = context.waitForPage(() -> {
         page.getByText("open new page").click();
       });
       System.out.println(newPage.evaluate("location.href"));
       

      NOTE: Use Page.waitForLoadState() to wait until the page gets to a particular state (you should not need it in most cases).

      Specified by:
      onPage in interface BrowserContext
    • offPage

      public void offPage(Consumer<Page> handler)
      Description copied from interface: BrowserContext
      Removes handler that was previously added with onPage(handler).
      Specified by:
      offPage in interface BrowserContext
    • onWebError

      public void onWebError(Consumer<WebError> handler)
      Description copied from interface: BrowserContext
      Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular page, use Page.onPageError() instead.
      Specified by:
      onWebError in interface BrowserContext
    • offWebError

      public void offWebError(Consumer<WebError> handler)
      Description copied from interface: BrowserContext
      Removes handler that was previously added with onWebError(handler).
      Specified by:
      offWebError in interface BrowserContext
    • onRequest

      public void onRequest(Consumer<Request> handler)
      Description copied from interface: BrowserContext
      Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To only listen for requests from a particular page, use Page.onRequest().

      In order to intercept and mutate requests, see BrowserContext.route() or Page.route().

      Specified by:
      onRequest in interface BrowserContext
    • offRequest

      public void offRequest(Consumer<Request> handler)
      Description copied from interface: BrowserContext
      Removes handler that was previously added with onRequest(handler).
      Specified by:
      offRequest in interface BrowserContext
    • onRequestFailed

      public void onRequestFailed(Consumer<Request> handler)
      Description copied from interface: BrowserContext
      Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page, use Page.onRequestFailed().

      NOTE: HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with BrowserContext.onRequestFinished() event and not with BrowserContext.onRequestFailed().

      Specified by:
      onRequestFailed in interface BrowserContext
    • offRequestFailed

      public void offRequestFailed(Consumer<Request> handler)
      Description copied from interface: BrowserContext
      Removes handler that was previously added with onRequestFailed(handler).
      Specified by:
      offRequestFailed in interface BrowserContext
    • onRequestFinished

      public void onRequestFinished(Consumer<Request> handler)
      Description copied from interface: BrowserContext
      Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is request, response and requestfinished. To listen for successful requests from a particular page, use Page.onRequestFinished().
      Specified by:
      onRequestFinished in interface BrowserContext
    • offRequestFinished

      public void offRequestFinished(Consumer<Request> handler)
      Description copied from interface: BrowserContext
      Removes handler that was previously added with onRequestFinished(handler).
      Specified by:
      offRequestFinished in interface BrowserContext
    • onResponse

      public void onResponse(Consumer<Response> handler)
      Description copied from interface: BrowserContext
      Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events is request, response and requestfinished. To listen for response events from a particular page, use Page.onResponse().
      Specified by:
      onResponse in interface BrowserContext
    • offResponse

      public void offResponse(Consumer<Response> handler)
      Description copied from interface: BrowserContext
      Removes handler that was previously added with onResponse(handler).
      Specified by:
      offResponse in interface BrowserContext
    • waitForEventWithTimeout

      private <T> T waitForEventWithTimeout(BrowserContextImpl.EventType eventType, Runnable code, Predicate<T> predicate, Double timeout)
    • waitForPage

      public Page waitForPage(BrowserContext.WaitForPageOptions options, Runnable code)
      Description copied from interface: BrowserContext
      Performs action and waits for a new Page to be created in the context. If predicate is provided, it passes Page value into the predicate function and waits for predicate(event) to return a truthy value. Will throw an error if the context closes before new Page is created.
      Specified by:
      waitForPage in interface BrowserContext
      Parameters:
      code - Callback that performs the action triggering the event.
    • waitForPageImpl

      private Page waitForPageImpl(BrowserContext.WaitForPageOptions options, Runnable code)
    • newCDPSession

      public CDPSession newCDPSession(Page page)
      Description copied from interface: BrowserContext
      NOTE: CDP sessions are only supported on Chromium-based browsers.

      Returns the newly created session.

      Specified by:
      newCDPSession in interface BrowserContext
      Parameters:
      page - Target to create new session for. For backwards-compatibility, this parameter is named page, but it can be a Page or Frame type.
    • newCDPSession

      public CDPSession newCDPSession(Frame frame)
      Description copied from interface: BrowserContext
      NOTE: CDP sessions are only supported on Chromium-based browsers.

      Returns the newly created session.

      Specified by:
      newCDPSession in interface BrowserContext
      Parameters:
      frame - Target to create new session for. For backwards-compatibility, this parameter is named page, but it can be a Page or Frame type.
    • close

      public void close()
      Description copied from interface: BrowserContext
      Closes the browser context. All the pages that belong to the browser context will be closed.

      NOTE: The default browser context cannot be closed.

      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface BrowserContext
    • cookies

      public List<Cookie> cookies(String url)
      Description copied from interface: BrowserContext
      If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.
      Specified by:
      cookies in interface BrowserContext
      Parameters:
      url - Optional list of URLs.
    • closeImpl

      private void closeImpl()
    • addCookies

      public void addCookies(List<Cookie> cookies)
      Description copied from interface: BrowserContext
      Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained via BrowserContext.cookies().

      **Usage**

      
       browserContext.addCookies(Arrays.asList(cookieObject1, cookieObject2));
       
      Specified by:
      addCookies in interface BrowserContext
      Parameters:
      cookies - Adds cookies to the browser context.

      For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com".

    • addInitScript

      public void addInitScript(String script)
      Description copied from interface: BrowserContext
      Adds a script which would be evaluated in one of the following scenarios:
      • Whenever a page is created in the browser context or is navigated.
      • Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is evaluated in the context of the newly attached frame.

      The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

      **Usage**

      An example of overriding Math.random before the page loads:

      
       // In your playwright script, assuming the preload.js file is in same directory.
       browserContext.addInitScript(Paths.get("preload.js"));
       

      NOTE: The order of evaluation of multiple scripts installed via BrowserContext.addInitScript() and Page.addInitScript() is not defined.

      Specified by:
      addInitScript in interface BrowserContext
      Parameters:
      script - Script to be evaluated in all pages in the browser context.
    • addInitScript

      public void addInitScript(Path path)
      Description copied from interface: BrowserContext
      Adds a script which would be evaluated in one of the following scenarios:
      • Whenever a page is created in the browser context or is navigated.
      • Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is evaluated in the context of the newly attached frame.

      The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

      **Usage**

      An example of overriding Math.random before the page loads:

      
       // In your playwright script, assuming the preload.js file is in same directory.
       browserContext.addInitScript(Paths.get("preload.js"));
       

      NOTE: The order of evaluation of multiple scripts installed via BrowserContext.addInitScript() and Page.addInitScript() is not defined.

      Specified by:
      addInitScript in interface BrowserContext
      Parameters:
      path - Script to be evaluated in all pages in the browser context.
    • addInitScriptImpl

      private void addInitScriptImpl(String script)
    • browser

      public BrowserImpl browser()
      Description copied from interface: BrowserContext
      Returns the browser instance of the context. If it was launched as a persistent context null gets returned.
      Specified by:
      browser in interface BrowserContext
    • clearCookies

      public void clearCookies()
      Description copied from interface: BrowserContext
      Clears context cookies.
      Specified by:
      clearCookies in interface BrowserContext
    • clearPermissions

      public void clearPermissions()
      Description copied from interface: BrowserContext
      Clears all permission overrides for the browser context.

      **Usage**

      
       BrowserContext context = browser.newContext();
       context.grantPermissions(Arrays.asList("clipboard-read"));
       // do stuff ..
       context.clearPermissions();
       
      Specified by:
      clearPermissions in interface BrowserContext
    • cookies

      public List<Cookie> cookies(List<String> urls)
      Description copied from interface: BrowserContext
      If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.
      Specified by:
      cookies in interface BrowserContext
      Parameters:
      urls - Optional list of URLs.
    • cookiesImpl

      private List<Cookie> cookiesImpl(List<String> urls)
    • exposeBinding

      public void exposeBinding(String name, BindingCallback playwrightBinding, BrowserContext.ExposeBindingOptions options)
      Description copied from interface: BrowserContext
      The method adds a function called name on the window object of every frame in every page in the context. When called, the function executes callback and returns a Promise which resolves to the return value of callback. If the callback returns a Promise, it will be awaited.

      The first argument of the callback function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }.

      See Page.exposeBinding() for page-only version.

      **Usage**

      An example of exposing page URL to all frames in all pages in the context:

      
       import com.microsoft.playwright.*;
      
       public class Example {
         public static void main(String[] args) {
           try (Playwright playwright = Playwright.create()) {
             BrowserType webkit = playwright.webkit()
             Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
             BrowserContext context = browser.newContext();
             context.exposeBinding("pageURL", (source, args) -> source.page().url());
             Page page = context.newPage();
             page.setContent("<script>\n" +
               "  async function onClick() {\n" +
               "    document.querySelector('div').textContent = await window.pageURL();\n" +
               "  }\n" +
               "</script>\n" +
               "<button onclick=\"onClick()\">Click me</button>\n" +
               "<div></div>");
             page.getByRole(AriaRole.BUTTON).click();
           }
         }
       }
       

      An example of passing an element handle:

      
       context.exposeBinding("clicked", (source, args) -> {
         ElementHandle element = (ElementHandle) args[0];
         System.out.println(element.textContent());
         return null;
       }, new BrowserContext.ExposeBindingOptions().setHandle(true));
       page.setContent("" +
         "<script>\n" +
         "  document.addEventListener('click', event => window.clicked(event.target));\n" +
         "</script>\n" +
         "<div>Click me</div>\n" +
         "<div>Or click me</div>\n");
       
      Specified by:
      exposeBinding in interface BrowserContext
      Parameters:
      name - Name of the function on the window object.
      playwrightBinding - Callback function that will be called in the Playwright's context.
    • exposeBindingImpl

      private void exposeBindingImpl(String name, BindingCallback playwrightBinding, BrowserContext.ExposeBindingOptions options)
    • exposeFunction

      public void exposeFunction(String name, FunctionCallback playwrightFunction)
      Description copied from interface: BrowserContext
      The method adds a function called name on the window object of every frame in every page in the context. When called, the function executes callback and returns a Promise which resolves to the return value of callback.

      If the callback returns a Promise, it will be awaited.

      See Page.exposeFunction() for page-only version.

      **Usage**

      An example of adding a sha256 function to all pages in the context:

      
       import com.microsoft.playwright.*;
      
       import java.nio.charset.StandardCharsets;
       import java.security.MessageDigest;
       import java.security.NoSuchAlgorithmException;
       import java.util.Base64;
      
       public class Example {
         public static void main(String[] args) {
           try (Playwright playwright = Playwright.create()) {
             BrowserType webkit = playwright.webkit()
             Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
             context.exposeFunction("sha256", args -> {
               String text = (String) args[0];
               MessageDigest crypto;
               try {
                 crypto = MessageDigest.getInstance("SHA-256");
               } catch (NoSuchAlgorithmException e) {
                 return null;
               }
               byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8));
               return Base64.getEncoder().encodeToString(token);
             });
             Page page = context.newPage();
             page.setContent("<script>\n" +
               "  async function onClick() {\n" +
               "    document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" +
               "  }\n" +
               "</script>\n" +
               "<button onclick=\"onClick()\">Click me</button>\n" +
               "<div></div>\n");
             page.getByRole(AriaRole.BUTTON).click();
           }
         }
       }
       
      Specified by:
      exposeFunction in interface BrowserContext
      Parameters:
      name - Name of the function on the window object.
      playwrightFunction - Callback function that will be called in the Playwright's context.
    • grantPermissions

      public void grantPermissions(List<String> permissions, BrowserContext.GrantPermissionsOptions options)
      Description copied from interface: BrowserContext
      Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.
      Specified by:
      grantPermissions in interface BrowserContext
      Parameters:
      permissions - A permission or an array of permissions to grant. Permissions can be one of the following values:
      • "geolocation"
      • "midi"
      • "midi-sysex" (system-exclusive midi)
      • "notifications"
      • "camera"
      • "microphone"
      • "background-sync"
      • "ambient-light-sensor"
      • "accelerometer"
      • "gyroscope"
      • "magnetometer"
      • "accessibility-events"
      • "clipboard-read"
      • "clipboard-write"
      • "payment-handler"
    • grantPermissionsImpl

      private void grantPermissionsImpl(List<String> permissions, BrowserContext.GrantPermissionsOptions options)
    • newPage

      public PageImpl newPage()
      Description copied from interface: BrowserContext
      Creates a new page in the browser context.
      Specified by:
      newPage in interface BrowserContext
    • newPageImpl

      private PageImpl newPageImpl()
    • pages

      public List<Page> pages()
      Description copied from interface: BrowserContext
      Returns all open pages in the context.
      Specified by:
      pages in interface BrowserContext
    • request

      public APIRequestContextImpl request()
      Description copied from interface: BrowserContext
      API testing helper associated with this context. Requests made with this API will use context cookies.
      Specified by:
      request in interface BrowserContext
    • route

      public void route(String url, Consumer<Route> handler, BrowserContext.RouteOptions options)
      Description copied from interface: BrowserContext
      Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

      NOTE: BrowserContext.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers to "block".

      **Usage**

      An example of a naive handler that aborts all image requests:

      
       BrowserContext context = browser.newContext();
       context.route("**\/*.{png,jpg,jpeg}", route -> route.abort());
       Page page = context.newPage();
       page.navigate("https://example.com");
       browser.close();
       

      or the same snippet using a regex pattern instead:

      
       BrowserContext context = browser.newContext();
       context.route(Pattern.compile("(\\.png$)|(\\.jpg$)"), route -> route.abort());
       Page page = context.newPage();
       page.navigate("https://example.com");
       browser.close();
       

      It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

      
       context.route("/api/**", route -> {
         if (route.request().postData().contains("my-string"))
           route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
         else
           route.resume();
       });
       

      Page routes (set up with Page.route()) take precedence over browser context routes when request matches both handlers.

      To remove a route with its handler you can use BrowserContext.unroute().

      NOTE: Enabling routing disables http cache.

      Specified by:
      route in interface BrowserContext
      Parameters:
      url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
      handler - handler function to route the request.
    • route

      public void route(Pattern url, Consumer<Route> handler, BrowserContext.RouteOptions options)
      Description copied from interface: BrowserContext
      Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

      NOTE: BrowserContext.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers to "block".

      **Usage**

      An example of a naive handler that aborts all image requests:

      
       BrowserContext context = browser.newContext();
       context.route("**\/*.{png,jpg,jpeg}", route -> route.abort());
       Page page = context.newPage();
       page.navigate("https://example.com");
       browser.close();
       

      or the same snippet using a regex pattern instead:

      
       BrowserContext context = browser.newContext();
       context.route(Pattern.compile("(\\.png$)|(\\.jpg$)"), route -> route.abort());
       Page page = context.newPage();
       page.navigate("https://example.com");
       browser.close();
       

      It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

      
       context.route("/api/**", route -> {
         if (route.request().postData().contains("my-string"))
           route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
         else
           route.resume();
       });
       

      Page routes (set up with Page.route()) take precedence over browser context routes when request matches both handlers.

      To remove a route with its handler you can use BrowserContext.unroute().

      NOTE: Enabling routing disables http cache.

      Specified by:
      route in interface BrowserContext
      Parameters:
      url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
      handler - handler function to route the request.
    • route

      public void route(Predicate<String> url, Consumer<Route> handler, BrowserContext.RouteOptions options)
      Description copied from interface: BrowserContext
      Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

      NOTE: BrowserContext.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers to "block".

      **Usage**

      An example of a naive handler that aborts all image requests:

      
       BrowserContext context = browser.newContext();
       context.route("**\/*.{png,jpg,jpeg}", route -> route.abort());
       Page page = context.newPage();
       page.navigate("https://example.com");
       browser.close();
       

      or the same snippet using a regex pattern instead:

      
       BrowserContext context = browser.newContext();
       context.route(Pattern.compile("(\\.png$)|(\\.jpg$)"), route -> route.abort());
       Page page = context.newPage();
       page.navigate("https://example.com");
       browser.close();
       

      It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

      
       context.route("/api/**", route -> {
         if (route.request().postData().contains("my-string"))
           route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
         else
           route.resume();
       });
       

      Page routes (set up with Page.route()) take precedence over browser context routes when request matches both handlers.

      To remove a route with its handler you can use BrowserContext.unroute().

      NOTE: Enabling routing disables http cache.

      Specified by:
      route in interface BrowserContext
      Parameters:
      url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
      handler - handler function to route the request.
    • routeFromHAR

      public void routeFromHAR(Path har, BrowserContext.RouteFromHAROptions options)
      Description copied from interface: BrowserContext
      If specified the network requests that are made in the context will be served from the HAR file. Read more about Replaying from HAR.

      Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers to "block".

      Specified by:
      routeFromHAR in interface BrowserContext
      Parameters:
      har - Path to a HAR file with prerecorded network data. If path is a relative path, then it is resolved relative to the current working directory.
    • route

      private void route(UrlMatcher matcher, Consumer<Route> handler, BrowserContext.RouteOptions options)
    • recordIntoHar

      void recordIntoHar(PageImpl page, Path har, BrowserContext.RouteFromHAROptions options)
    • setDefaultNavigationTimeout

      public void setDefaultNavigationTimeout(double timeout)
      Description copied from interface: BrowserContext
      This setting will change the default maximum navigation time for the following methods and related shortcuts:

      NOTE: Page.setDefaultNavigationTimeout() and Page.setDefaultTimeout() take priority over BrowserContext.setDefaultNavigationTimeout().

      Specified by:
      setDefaultNavigationTimeout in interface BrowserContext
      Parameters:
      timeout - Maximum navigation time in milliseconds
    • setDefaultNavigationTimeoutImpl

      void setDefaultNavigationTimeoutImpl(Double timeout)
    • setDefaultTimeout

      public void setDefaultTimeout(double timeout)
      Description copied from interface: BrowserContext
      This setting will change the default maximum time for all the methods accepting timeout option.

      NOTE: Page.setDefaultNavigationTimeout(), Page.setDefaultTimeout() and BrowserContext.setDefaultNavigationTimeout() take priority over BrowserContext.setDefaultTimeout().

      Specified by:
      setDefaultTimeout in interface BrowserContext
      Parameters:
      timeout - Maximum time in milliseconds
    • setDefaultTimeoutImpl

      void setDefaultTimeoutImpl(Double timeout)
    • setExtraHTTPHeaders

      public void setExtraHTTPHeaders(Map<String,String> headers)
      Description copied from interface: BrowserContext
      The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged with page-specific extra HTTP headers set with Page.setExtraHTTPHeaders(). If page overrides a particular header, page-specific header value will be used instead of the browser context header value.

      NOTE: BrowserContext.setExtraHTTPHeaders() does not guarantee the order of headers in the outgoing requests.

      Specified by:
      setExtraHTTPHeaders in interface BrowserContext
      Parameters:
      headers - An object containing additional HTTP headers to be sent with every request. All header values must be strings.
    • setGeolocation

      public void setGeolocation(Geolocation geolocation)
      Description copied from interface: BrowserContext
      Sets the context's geolocation. Passing null or undefined emulates position unavailable.

      **Usage**

      
       browserContext.setGeolocation(new Geolocation(59.95, 30.31667));
       

      NOTE: Consider using BrowserContext.grantPermissions() to grant permissions for the browser context pages to read its geolocation.

      Specified by:
      setGeolocation in interface BrowserContext
    • setOffline

      public void setOffline(boolean offline)
      Specified by:
      setOffline in interface BrowserContext
      Parameters:
      offline - Whether to emulate network being offline for the browser context.
    • storageState

      public String storageState(BrowserContext.StorageStateOptions options)
      Description copied from interface: BrowserContext
      Returns storage state for this browser context, contains current cookies and local storage snapshot.
      Specified by:
      storageState in interface BrowserContext
    • tracing

      public TracingImpl tracing()
      Specified by:
      tracing in interface BrowserContext
    • unroute

      public void unroute(String url, Consumer<Route> handler)
      Description copied from interface: BrowserContext
      Removes a route created with BrowserContext.route(). When handler is not specified, removes all routes for the url.
      Specified by:
      unroute in interface BrowserContext
      Parameters:
      url - A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with BrowserContext.route().
      handler - Optional handler function used to register a routing with BrowserContext.route().
    • unroute

      public void unroute(Pattern url, Consumer<Route> handler)
      Description copied from interface: BrowserContext
      Removes a route created with BrowserContext.route(). When handler is not specified, removes all routes for the url.
      Specified by:
      unroute in interface BrowserContext
      Parameters:
      url - A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with BrowserContext.route().
      handler - Optional handler function used to register a routing with BrowserContext.route().
    • unroute

      public void unroute(Predicate<String> url, Consumer<Route> handler)
      Description copied from interface: BrowserContext
      Removes a route created with BrowserContext.route(). When handler is not specified, removes all routes for the url.
      Specified by:
      unroute in interface BrowserContext
      Parameters:
      url - A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with BrowserContext.route().
      handler - Optional handler function used to register a routing with BrowserContext.route().
    • waitForCondition

      public void waitForCondition(BooleanSupplier predicate, BrowserContext.WaitForConditionOptions options)
      Description copied from interface: BrowserContext
      The method will block until the condition returns true. All Playwright events will be dispatched while the method is waiting for the condition.

      **Usage**

      Use the method to wait for a condition that depends on page events:

      
       List<String> failedUrls = new ArrayList<>();
       context.onResponse(response -> {
         if (!response.ok()) {
           failedUrls.add(response.url());
         }
       });
       page1.getByText("Create user").click();
       page2.getByText("Submit button").click();
       context.waitForCondition(() -> failedUrls.size() > 3);
       
      Specified by:
      waitForCondition in interface BrowserContext
      Parameters:
      predicate - Condition to wait for.
    • waitForConsoleMessage

      public ConsoleMessage waitForConsoleMessage(BrowserContext.WaitForConsoleMessageOptions options, Runnable code)
      Description copied from interface: BrowserContext
      Performs action and waits for a ConsoleMessage to be logged by in the pages in the context. If predicate is provided, it passes ConsoleMessage value into the predicate function and waits for predicate(message) to return a truthy value. Will throw an error if the page is closed before the BrowserContext.onConsoleMessage() event is fired.
      Specified by:
      waitForConsoleMessage in interface BrowserContext
      Parameters:
      code - Callback that performs the action triggering the event.
    • waitForConsoleMessageImpl

      private ConsoleMessage waitForConsoleMessageImpl(BrowserContext.WaitForConsoleMessageOptions options, Runnable code)
    • unroute

      private void unroute(UrlMatcher matcher, Consumer<Route> handler)
    • updateInterceptionPatterns

      private void updateInterceptionPatterns()
    • handleRoute

      void handleRoute(RouteImpl route)
    • pause

      WaitableResult<com.google.gson.JsonElement> pause()
    • handleEvent

      protected void handleEvent(String event, com.google.gson.JsonObject params)
      Overrides:
      handleEvent in class ChannelOwner
    • didClose

      void didClose()
    • createTempFile

      WritableStream createTempFile(String name)