Class: Playwright::BrowserContext

Inherits:
PlaywrightApi show all
Defined in:
lib/playwright_api/browser_context.rb

Overview

  • extends: [EventEmitter]

BrowserContexts provide a way to operate multiple independent browser sessions.

If a page opens another page, e.g. with a window.open call, the popup will belong to the parent page’s browser context.

Playwright allows creation of “incognito” browser contexts with ‘browser.newContext()` method. “Incognito” browser contexts don’t write any browsing data to disk.

“‘js // Create a new incognito browser context const context = await browser.newContext(); // Create a new page inside context. const page = await context.newPage(); await page.goto(’example.com’); // Dispose context once it’s no longer needed. await context.close(); “‘

“‘python async # create a new incognito browser context context = await browser.new_context() # create a new page inside context. page = await context.new_page() await page.goto(“example.com”) # dispose context once it“s no longer needed. await context.close() “`

“‘python sync # create a new incognito browser context context = browser.new_context() # create a new page inside context. page = context.new_page() page.goto(“example.com”) # dispose context once it“s no longer needed. context.close() “`

Instance Method Summary collapse

Methods inherited from PlaywrightApi

#==, from_channel_owner, #initialize

Constructor Details

This class inherits a constructor from Playwright::PlaywrightApi

Instance Method Details

#add_cookies(cookies) ⇒ Object

Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained via [‘method: BrowserContext.cookies`].

“‘js await browserContext.addCookies([cookieObject1, cookieObject2]); “`

“‘python async await browser_context.add_cookies([cookie_object1, cookie_object2]) “`

“‘python sync browser_context.add_cookies([cookie_object1, cookie_object2]) “`

Raises:

  • (NotImplementedError)


59
60
61
# File 'lib/playwright_api/browser_context.rb', line 59

def add_cookies(cookies)
  raise NotImplementedError.new('add_cookies is not implemented yet.')
end

#add_init_script(script, arg: nil) ⇒ Object

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.

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

“‘js browser // preload.js Math.random = () => 42; “`

“‘js // In your playwright script, assuming the preload.js file is in same directory. await browserContext.addInitScript(

path: 'preload.js'

); “‘

“‘python async # in your playwright script, assuming the preload.js file is in same directory. await browser_context.add_init_script(path=“preload.js”) “`

“‘python sync # in your playwright script, assuming the preload.js file is in same directory. browser_context.add_init_script(path=“preload.js”) “`

> NOTE: The order of evaluation of multiple scripts installed via [‘method: BrowserContext.addInitScript`] and

‘method: Page.addInitScript`

is not defined.

Raises:

  • (NotImplementedError)


99
100
101
# File 'lib/playwright_api/browser_context.rb', line 99

def add_init_script(script, arg: nil)
  raise NotImplementedError.new('add_init_script is not implemented yet.')
end

#after_initializeObject



580
581
582
# File 'lib/playwright_api/browser_context.rb', line 580

def after_initialize
  wrap_impl(@impl.after_initialize)
end

#browserObject

Returns the browser instance of the context. If it was launched as a persistent context null gets returned.

Raises:

  • (NotImplementedError)


104
105
106
# File 'lib/playwright_api/browser_context.rb', line 104

def browser
  raise NotImplementedError.new('browser is not implemented yet.')
end

#browser=(req) ⇒ Object



585
586
587
# File 'lib/playwright_api/browser_context.rb', line 585

def browser=(req)
  wrap_impl(@impl.browser=(req))
end

#clear_cookiesObject

Clears context cookies.

Raises:

  • (NotImplementedError)


109
110
111
# File 'lib/playwright_api/browser_context.rb', line 109

def clear_cookies
  raise NotImplementedError.new('clear_cookies is not implemented yet.')
end

#clear_permissionsObject

Clears all permission overrides for the browser context.

“‘js const context = await browser.newContext(); await context.grantPermissions(); // do stuff .. context.clearPermissions(); “`

“‘python async context = await browser.new_context() await context.grant_permissions() # do stuff .. context.clear_permissions() “`

“‘python sync context = browser.new_context() context.grant_permissions() # do stuff .. context.clear_permissions() “`

Raises:

  • (NotImplementedError)


136
137
138
# File 'lib/playwright_api/browser_context.rb', line 136

def clear_permissions
  raise NotImplementedError.new('clear_permissions is not implemented yet.')
end

#closeObject

Closes the browser context. All the pages that belong to the browser context will be closed.

> NOTE: The default browser context cannot be closed.



143
144
145
# File 'lib/playwright_api/browser_context.rb', line 143

def close
  wrap_impl(@impl.close)
end

#cookies(urls: nil) ⇒ Object

If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.

Raises:

  • (NotImplementedError)


149
150
151
# File 'lib/playwright_api/browser_context.rb', line 149

def cookies(urls: nil)
  raise NotImplementedError.new('cookies is not implemented yet.')
end

#expect_event(event, optionsOrPredicate: nil) ⇒ Object

Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the context closes before the event is fired. Returns the event data value.

“‘js const [page, _] = await Promise.all([

context.waitForEvent('page'),
page.click('button')

]); “‘

“‘python async async with context.expect_event(“page”) as event_info:

await page.click("button")

page = await event_info.value “‘

“‘python sync with context.expect_event(“page”) as event_info:

page.click("button")

page = event_info.value “‘

Raises:

  • (NotImplementedError)


570
571
572
# File 'lib/playwright_api/browser_context.rb', line 570

def expect_event(event, optionsOrPredicate: nil)
  raise NotImplementedError.new('expect_event is not implemented yet.')
end

#expose_binding(name, callback, handle: nil) ⇒ Object

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 [‘method: Page.exposeBinding`] for page-only version.

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

“‘js const { webkit } = require(’playwright’); // Or ‘chromium’ or ‘firefox’.

(async () => {

const browser = await webkit.launch({ headless: false });
const context = await browser.newContext();
await context.exposeBinding('pageURL', ({ page }) => page.url());
const page = await context.newPage();
await page.setContent(`
  <script>
    async function onClick() {
      document.querySelector('div').textContent = await window.pageURL();
    }
  </script>
  <button onclick="onClick()">Click me</button>
  <div></div>
`);
await page.click('button');

})(); “‘

“‘python async import asyncio from playwright.async_api import async_playwright

async def run(playwright):

webkit = playwright.webkit
browser = await webkit.launch(headless=false)
context = await browser.new_context()
await context.expose_binding("pageURL", lambda source: source["page"].url)
page = await context.new_page()
await page.set_content("""
<script>
  async function onClick() {
    document.querySelector('div').textContent = await window.pageURL();
  }
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
await page.click("button")

async def main():

async with async_playwright() as playwright:
    await run(playwright)

asyncio.run(main()) “‘

“‘python sync from playwright.sync_api import sync_playwright

def run(playwright):

webkit = playwright.webkit
browser = webkit.launch(headless=false)
context = browser.new_context()
context.expose_binding("pageURL", lambda source: source["page"].url)
page = context.new_page()
page.set_content("""
<script>
  async function onClick() {
    document.querySelector('div').textContent = await window.pageURL();
  }
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
page.click("button")

with sync_playwright() as playwright:

run(playwright)

“‘

An example of passing an element handle:

“‘js await context.exposeBinding(’clicked’, async (source, element) =>

console.log(await element.textContent());

, { handle: true }); await page.setContent(‘

<script>
  document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>

‘); “`

“‘python async async def print(source, element):

print(await element.text_content())

await context.expose_binding(“clicked”, print, handle=true) await page.set_content(“”“

<script>
  document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>

“”“) “‘

“‘python sync def print(source, element):

print(element.text_content())

context.expose_binding(“clicked”, print, handle=true) page.set_content(“”“

<script>
  document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>

“”“) “‘

Raises:

  • (NotImplementedError)


280
281
282
# File 'lib/playwright_api/browser_context.rb', line 280

def expose_binding(name, callback, handle: nil)
  raise NotImplementedError.new('expose_binding is not implemented yet.')
end

#expose_function(name, callback) ⇒ Object

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 [‘method: Page.exposeFunction`] for page-only version.

An example of adding an md5 function to all pages in the context:

“‘js const { webkit } = require(’playwright’); // Or ‘chromium’ or ‘firefox’. const crypto = require(‘crypto’);

(async () => {

const browser = await webkit.launch({ headless: false });
const context = await browser.newContext();
await context.exposeFunction('md5', text => crypto.createHash('md5').update(text).digest('hex'));
const page = await context.newPage();
await page.setContent(`
  <script>
    async function onClick() {
      document.querySelector('div').textContent = await window.md5('PLAYWRIGHT');
    }
  </script>
  <button onclick="onClick()">Click me</button>
  <div></div>
`);
await page.click('button');

})(); “‘

“‘python async import asyncio import hashlib from playwright.async_api import async_playwright

async def sha1(text):

m = hashlib.sha1()
m.update(bytes(text, "utf8"))
return m.hexdigest()

async def run(playwright):

webkit = playwright.webkit
browser = await webkit.launch(headless=False)
context = await browser.new_context()
await context.expose_function("sha1", sha1)
page = await context.new_page()
await page.set_content("""
    <script>
      async function onClick() {
        document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');
      }
    </script>
    <button onclick="onClick()">Click me</button>
    <div></div>
""")
await page.click("button")

async def main():

async with async_playwright() as playwright:
    await run(playwright)

asyncio.run(main()) “‘

“‘python sync import hashlib from playwright.sync_api import sync_playwright

def sha1(text):

m = hashlib.sha1()
m.update(bytes(text, "utf8"))
return m.hexdigest()

def run(playwright):

webkit = playwright.webkit
browser = webkit.launch(headless=False)
context = browser.new_context()
context.expose_function("sha1", sha1)
page = context.new_page()
page.expose_function("sha1", sha1)
page.set_content("""
    <script>
      async function onClick() {
        document.querySelector('div').textContent = await window.sha1('PLAYWRIGHT');
      }
    </script>
    <button onclick="onClick()">Click me</button>
    <div></div>
""")
page.click("button")

with sync_playwright() as playwright:

run(playwright)

“‘

Raises:

  • (NotImplementedError)


381
382
383
# File 'lib/playwright_api/browser_context.rb', line 381

def expose_function(name, callback)
  raise NotImplementedError.new('expose_function is not implemented yet.')
end

#grant_permissions(permissions, origin: nil) ⇒ Object

Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.

Raises:

  • (NotImplementedError)


387
388
389
# File 'lib/playwright_api/browser_context.rb', line 387

def grant_permissions(permissions, origin: nil)
  raise NotImplementedError.new('grant_permissions is not implemented yet.')
end

#new_pageObject

Creates a new page in the browser context.



392
393
394
# File 'lib/playwright_api/browser_context.rb', line 392

def new_page
  wrap_impl(@impl.new_page)
end

#off(event, callback) ⇒ Object

– inherited from EventEmitter –



602
603
604
# File 'lib/playwright_api/browser_context.rb', line 602

def off(event, callback)
  wrap_impl(@impl.off(event, callback))
end

#on(event, callback) ⇒ Object

– inherited from EventEmitter –



596
597
598
# File 'lib/playwright_api/browser_context.rb', line 596

def on(event, callback)
  wrap_impl(@impl.on(event, callback))
end

#once(event, callback) ⇒ Object

– inherited from EventEmitter –



608
609
610
# File 'lib/playwright_api/browser_context.rb', line 608

def once(event, callback)
  wrap_impl(@impl.once(event, callback))
end

#options=(req) ⇒ Object



590
591
592
# File 'lib/playwright_api/browser_context.rb', line 590

def options=(req)
  wrap_impl(@impl.options=(req))
end

#owner_page=(req) ⇒ Object



575
576
577
# File 'lib/playwright_api/browser_context.rb', line 575

def owner_page=(req)
  wrap_impl(@impl.owner_page=(req))
end

#pagesObject

Returns all open pages in the context. Non visible pages, such as ‘“background_page”`, will not be listed here. You can find them using [`method: ChromiumBrowserContext.backgroundPages`].



398
399
400
# File 'lib/playwright_api/browser_context.rb', line 398

def pages
  wrap_impl(@impl.pages)
end

#route(url, handler) ⇒ Object

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.

An example of a naïve handler that aborts all image requests:

“‘js const context = await browser.newContext(); await context.route(’*/.png,jpg,jpeg‘, route => route.abort()); const page = await context.newPage(); await page.goto(’example.com’); await browser.close(); “‘

“‘python async context = await browser.new_context() page = await context.new_page() await context.route(“*/.png,jpg,jpeg”, lambda route: route.abort()) await page.goto(“example.com”) await browser.close() “`

“‘python sync context = browser.new_context() page = context.new_page() context.route(“*/.png,jpg,jpeg”, lambda route: route.abort()) page.goto(“example.com”) browser.close() “`

or the same snippet using a regex pattern instead:

“‘js const context = await browser.newContext(); await context.route(/(.png$)|(.jpg$)/, route => route.abort()); const page = await context.newPage(); await page.goto(’example.com’); await browser.close(); “‘

“‘python async context = await browser.new_context() page = await context.new_page() await context.route(re.compile(r“(.png$)|(.jpg$)”), lambda route: route.abort()) page = await context.new_page() await page.goto(“example.com”) await browser.close() “`

“‘python sync context = browser.new_context() page = context.new_page() context.route(re.compile(r“(.png$)|(.jpg$)”), lambda route: route.abort()) page = await context.new_page() page = context.new_page() page.goto(“example.com”) browser.close() “`

Page routes (set up with [‘method: Page.route`]) take precedence over browser context routes when request matches both handlers.

> NOTE: Enabling routing disables http cache.

Raises:

  • (NotImplementedError)


466
467
468
# File 'lib/playwright_api/browser_context.rb', line 466

def route(url, handler)
  raise NotImplementedError.new('route is not implemented yet.')
end

#set_default_navigation_timeout(timeout) ⇒ Object Also known as: default_navigation_timeout=

This setting will change the default maximum navigation time for the following methods and related shortcuts:

  • ‘method: Page.goBack`
  • ‘method: Page.goForward`
  • ‘method: Page.goto`
  • ‘method: Page.reload`
  • ‘method: Page.setContent`
  • ‘method: Page.waitForNavigation`

> NOTE: [‘method: Page.setDefaultNavigationTimeout`] and [`method: Page.setDefaultTimeout`] take priority over [`method: BrowserContext.setDefaultNavigationTimeout`].

Raises:

  • (NotImplementedError)


480
481
482
# File 'lib/playwright_api/browser_context.rb', line 480

def set_default_navigation_timeout(timeout)
  raise NotImplementedError.new('set_default_navigation_timeout is not implemented yet.')
end

#set_default_timeout(timeout) ⇒ Object Also known as: default_timeout=

This setting will change the default maximum time for all the methods accepting timeout option.

> NOTE: [‘method: Page.setDefaultNavigationTimeout`], [`method: Page.setDefaultTimeout`] and

‘method: BrowserContext.setDefaultNavigationTimeout`

take priority over [‘method: BrowserContext.setDefaultTimeout`].

Raises:

  • (NotImplementedError)


489
490
491
# File 'lib/playwright_api/browser_context.rb', line 489

def set_default_timeout(timeout)
  raise NotImplementedError.new('set_default_timeout is not implemented yet.')
end

#set_extra_http_headers(headers) ⇒ Object Also known as: extra_http_headers=

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 [‘method: Page.setExtraHTTPHeaders`]. If page overrides a particular header, page-specific header value will be used instead of the browser context header value.

> NOTE: [‘method: BrowserContext.setExtraHTTPHeaders`] does not guarantee the order of headers in the outgoing requests.

Raises:

  • (NotImplementedError)


499
500
501
# File 'lib/playwright_api/browser_context.rb', line 499

def set_extra_http_headers(headers)
  raise NotImplementedError.new('set_extra_http_headers is not implemented yet.')
end

#set_geolocation(geolocation) ⇒ Object Also known as: geolocation=

Sets the context’s geolocation. Passing null or undefined emulates position unavailable.

“‘js await browserContext.setGeolocation(59.95, longitude: 30.31667); “`

“‘python async await browser_context.set_geolocation(59.95, “longitude”: 30.31667) “`

“‘python sync browser_context.set_geolocation(59.95, “longitude”: 30.31667) “`

> NOTE: Consider using [‘method: BrowserContext.grantPermissions`] to grant permissions for the browser context pages to read its geolocation.

Raises:

  • (NotImplementedError)


521
522
523
# File 'lib/playwright_api/browser_context.rb', line 521

def set_geolocation(geolocation)
  raise NotImplementedError.new('set_geolocation is not implemented yet.')
end

#set_http_credentials(httpCredentials) ⇒ Object Also known as: http_credentials=

DEPRECATED Browsers may cache credentials after successful authentication. Create a new browser context instead.

Raises:

  • (NotImplementedError)


527
528
529
# File 'lib/playwright_api/browser_context.rb', line 527

def set_http_credentials(httpCredentials)
  raise NotImplementedError.new('set_http_credentials is not implemented yet.')
end

#set_offline(offline) ⇒ Object Also known as: offline=

Raises:

  • (NotImplementedError)


532
533
534
# File 'lib/playwright_api/browser_context.rb', line 532

def set_offline(offline)
  raise NotImplementedError.new('set_offline is not implemented yet.')
end

#storage_state(path: nil) ⇒ Object

Returns storage state for this browser context, contains current cookies and local storage snapshot.

Raises:

  • (NotImplementedError)


538
539
540
# File 'lib/playwright_api/browser_context.rb', line 538

def storage_state(path: nil)
  raise NotImplementedError.new('storage_state is not implemented yet.')
end

#unroute(url, handler: nil) ⇒ Object

Removes a route created with [‘method: BrowserContext.route`]. When handler is not specified, removes all routes for the url.

Raises:

  • (NotImplementedError)


544
545
546
# File 'lib/playwright_api/browser_context.rb', line 544

def unroute(url, handler: nil)
  raise NotImplementedError.new('unroute is not implemented yet.')
end