ddp_utils.browser.facade.browser¶
import ddp_utils.browser.facade.browser
Primary synchronous backend-neutral browser facade.
- class ddp_utils.browser.facade.browser.Browser(session: BrowserSession, config: BrowserConfig)¶
Bases:
objectExpose one stable synchronous API over a neutral owned session.
Parameters
Name
Type
Description
session
Neutral lifecycle session.
config
Effective immutable browser configuration.
Examples
Write business logic once for Selenium or Playwright:
with BrowserFactory().open(config) as browser: browser.go("https://example.com") browser.find("button", text="Search", condition="clickable").click()
Bind lifecycle, configuration, and facade services.
Parameters
Name
Type
Description
session
Started neutral browser session.
config
Effective validated configuration.
Examples
Factories create the facade after backend startup:
browser = Browser(session, config)
- add_command_listener(callback: Callable[[str, str], Any]) int¶
Subscribe to neutral browser command boundaries.
Parameters
Name
Type
Description
callback
Callable[[str, str], Any]
Function receiving
phaseand stable command name.Returns
Type
Description
int
Integer token accepted by
remove_command_listener().Raises
Exception
Description
TypeError
callbackis not callable.Examples
Register a CAPTCHA queue delivery boundary:
token = browser.add_command_listener(on_command)
- remove_command_listener(token: int) None¶
Remove one neutral command listener idempotently.
Parameters
Name
Type
Description
token
int
Token returned by
add_command_listener().Examples
browser.remove_command_listener(token).
- property config: BrowserConfig¶
Return the effective immutable browser configuration.
Returns
Configuration used to create this session.
Examples
Read the configured navigation timeout:
print(browser.config.timeouts.navigation)
- property descriptor: BackendDescriptor¶
Return immutable concrete backend identity and capabilities.
Returns
Active backend descriptor.
Examples
Record the concrete provider:
print(browser.descriptor.provider)
- property native: Any¶
Return the explicit backend-native session objects.
Returns
Selenium native objects, Playwright native objects, or native process information.
Examples
Use an unavoidable provider-only feature deliberately:
native = browser.native
- property closed: bool¶
Return whether the browser lifecycle is closed.
Returns
Trueafter session cleanup.Examples
Avoid scheduling new work after cleanup:
if browser.closed: return
- property wait: BrowserWait¶
Return the session-bound wait facade.
Returns
Stable synchronous wait helper.
Examples
Wait for an arbitrary project predicate:
browser.wait.until(lambda b: b.title == "Ready")
- property page: Any¶
Return the active native Playwright-shaped page.
Returns
Active Playwright or Camoufox page, or
Nonefor Selenium.Note
Business code should prefer neutral facade methods. This property is an explicit escape hatch for provider-specific operations.
Examples
Bring a Playwright page to the foreground deliberately:
if browser.is_playwright: browser.page.bring_to_front()
- property pages: BrowserPages¶
Return the top-level page and window service.
Returns
Session-bound neutral page service.
Examples
Open and later close a temporary page:
temporary = browser.pages.open("https://example.com") browser.pages.close(temporary)
- property frames: BrowserFrames¶
Return the frame navigation service.
Returns
Session-bound neutral frame service.
Examples
Limit searches to one frame:
with browser.frames.use(0): browser.find("button", required=True)
- property dialogs: BrowserDialogs¶
Return the JavaScript dialog service.
Returns
Session-bound neutral dialog service.
Examples
Accept a confirmation created by an action:
result = browser.dialogs.handle(button.click)
- property cookies: BrowserCookies¶
Return the browser cookie service.
Returns
Session-bound neutral cookie service.
Examples
Store one project cookie:
browser.cookies.set("project", "59-IN")
- property storage: BrowserStorage¶
Return localStorage and sessionStorage services.
Returns
Session-bound neutral storage aggregate.
Examples
Store a local cursor:
browser.storage.local.set("cursor", "5")
- property keyboard: BrowserKeyboard¶
Return normalized keyboard input.
Returns
Session-bound keyboard service.
Examples
Type into the focused control:
browser.keyboard.type("John", delay=0.04)
- property mouse: BrowserMouse¶
Return normalized mouse input.
Returns
Session-bound mouse service.
Examples
Scroll the active page:
browser.mouse.wheel(0, 600)
- property touchscreen: BrowserTouchscreen¶
Return normalized touchscreen input.
Returns
Session-bound touchscreen service.
Examples
Tap a mobile control:
browser.touchscreen.tap(40, 40)
- property cdp: BrowserCDP¶
Return raw Chrome DevTools Protocol access.
Returns
CDP facade whose
availableproperty states actual support.Examples
Execute a guarded raw command:
if browser.cdp.available: browser.cdp.cmd("Browser.getVersion")
- property bidi: BrowserBiDi¶
Return synchronous WebDriver BiDi access when available.
Returns
BiDi facade with honest soft-unsupported results.
Examples
Check before invoking a raw command:
if browser.bidi.available: browser.bidi.cmd("session.status")
- property extensions: BrowserExtensions¶
Return browser extension inventory and lifecycle operations.
Returns
Session-bound extension service.
Examples
Verify one startup extension:
status = browser.extensions.verify("Windscribe")
- property proxy: BrowserProxy¶
Return redacted proxy state and coherent controller operations.
Returns
Session-bound proxy service.
Examples
Verify a configured proxy:
result = browser.proxy.verify(timeout=10)
- property network: BrowserNetwork¶
Return normalized network observation and control.
Returns
Session-bound network service.
Examples
Observe a result API:
browser.network.start() response = browser.network.wait_response( url="*/results*", timeout=20 )
- property downloads: BrowserDownloads¶
Return download and blob-file lifecycle operations.
Returns
Session-bound download service.
Examples
Capture a click-triggered file:
button.click() download = browser.downloads.wait(timeout=30)
- property human: BrowserHuman¶
Return optional human-paced actions built on the neutral facade.
Returns
Session-bound human interaction service.
Examples
Type with bounded timing variation:
browser.human.type(field, "Smith", clear=True)
- property emulation: BrowserEmulation¶
Return runtime browser-emulation controls.
Returns
Session-bound emulation service. Unsupported changes return a structured
CapabilityResultinstead of being ignored.Examples
Set a mobile-sized viewport:
browser.emulation.viewport(390, 844)
- property logs: BrowserLogs¶
Return normalized browser and page logs.
Returns
Session-bound log collection service.
Examples
Inspect JavaScript failures after a workflow:
errors = browser.logs.javascript_errors()
- property tracing: BrowserTracing¶
Return trace recording controls.
Returns
Backend-aware tracing service.
Examples
Start a trace before a sensitive sequence:
browser.tracing.start(screenshots=True)
- property events: BrowserEvents¶
Return subscriptions and persistent browser-state watchers.
Returns
Event subscriptions, one-shot waits, and DOM or page watchers.
Examples
Subscribe to normalized events:
subscription = browser.events.on("console", print)
Register a persistent page condition:
browser.events.add_watcher( name="confirmation", when={"css": ".confirmation", "condition": "visible"}, callback=handle_confirmation, )
- property capabilities: BrowserCapabilities¶
Return capability discovery and enforcement helpers.
Returns
Stable capability service for the active backend.
Examples
Guard optional CDP code:
if browser.capabilities.has("cdp"): browser.cdp.cmd("Network.enable")
- property expect: BrowserExpect¶
Return synchronous semantic assertions.
Returns
Assertion service backed by neutral facade waits.
Examples
Assert that a result heading becomes visible:
browser.expect.visible("h1", timeout=10)
- property is_selenium: bool¶
Return whether the provider uses Selenium/WebDriver.
Returns
Truefor Selenium and SeleniumBase providers.Examples
Isolate intentionally provider-specific code:
if browser.is_selenium: driver = browser.native.driver
- property is_playwright: bool¶
Return whether the provider uses Playwright-shaped objects.
Returns
Truefor Playwright and Camoufox providers.Examples
Isolate an intentional native page call:
if browser.is_playwright: page = browser.native.page
- property url: str¶
Return the active page URL.
Returns
Current URL.
Raises
Exception
Description
The backend has no DOM capability.
Examples
Verify a navigation target:
assert browser.url.endswith("/results")
- property title: str¶
Return the active page title.
Returns
Current document title.
Raises
Exception
Description
The backend has no DOM capability.
Examples
Wait for a result page:
browser.wait.until(lambda b: "Results" in b.title)
- property html: str¶
Return serialized active-page HTML.
Returns
Current document markup.
Raises
Exception
Description
The backend has no DOM capability.
Examples
Preserve HTML for diagnostics:
snapshot = browser.html
- property ready_state: str¶
Return the current document readiness state.
Returns
Browser-reported
loading,interactive, orcompletestate.Raises
Exception
Description
The backend has no JavaScript capability.
Examples
Wait until the current document is complete:
browser.wait.until(lambda _: browser.ready_state == "complete")
- property backend: str¶
Return the concrete backend provider name.
Returns
Provider name such as
selenium,seleniumbase,playwright,camoufox, orsystem.Examples
Record the selected implementation in diagnostics:
diagnostics["backend"] = browser.backend
- property browser_name: str¶
Return the normalized browser product name.
Returns
Product name such as
chrome,edge,brave, orfirefox.Examples
Guard a product-specific business workaround:
if browser.browser_name == "firefox": use_firefox_workaround()
- property sb: Any¶
Return SeleniumBase only when the active provider exposes it.
Returns
SeleniumBase driver object.
Raises
Exception
Description
The active backend is not SeleniumBase.
Examples
Use a CAPTCHA helper only after checking support:
if browser.capabilities.has("seleniumbase"): browser.sb.uc_open_with_reconnect(url)
- capability(capability: BrowserCapability | str) CapabilityResult[BrowserCapability]¶
Return structured support information for one capability.
Parameters
Name
Type
Description
capability
BrowserCapability | str
Stable capability name.
Returns
Type
Description
Supported or unsupported capability result.
Examples
Check CDP without technology branching:
if browser.capability("cdp").supported: use_cdp()
- open(url: str, *, timeout: float | None = None, wait_until: str = 'load') Browser¶
Navigate the active page and return this browser.
Parameters
Name
Type
Description
url
str
Destination URL.
timeout
float | None
Optional navigation timeout in seconds.
wait_until
str
Playwright navigation completion state. Selenium waits according to its configured page-load strategy.
Returns
Type
Description
This browser for fluent project code.
Raises
Exception
Description
The backend has no DOM capability.
Examples
Navigate before structured search:
browser.open("https://example.com").find("h1")
- go(url: str) Browser¶
Navigate using the historical fluent alias for
open().Parameters
Name
Type
Description
url
str
Destination URL.
Returns
Type
Description
This browser.
Examples
Existing project code may keep the concise alias:
browser.go("https://example.com")
- get(url: str, *, timeout: float | None = None, wait_until: str = 'load') Browser¶
Navigate using the WebDriver-compatible alias for
open().Parameters
Name
Type
Description
url
str
Destination URL.
timeout
float | None
Optional navigation timeout in seconds.
wait_until
str
Playwright completion state. Selenium uses its page load strategy.
Returns
Type
Description
This browser for fluent project code.
Raises
Exception
Description
If the backend cannot navigate a DOM.
Examples
Use familiar WebDriver naming without backend branching:
browser.get("https://example.com", timeout=30)
- get_ip_state(url: str = 'https://ipwho.is/', *, timeout: float | None = None) dict[str, Any]¶
Return the public network and GeoIP state observed by this browser.
The lookup is opened inside the active browser, so its result reflects the browser’s effective proxy or VPN rather than the Python process. The current page is intentionally replaced by the JSON endpoint.
Parameters
Name
Type
Description
url
str
JSON endpoint compatible with
https://ipwho.is/.timeout
float | None
Optional navigation timeout in seconds.
Returns
Type
Description
dict[str, Any]
Parsed JSON object returned to the browser.
Raises
Exception
Description
If the response body is empty, invalid JSON, or not a JSON object.
If the backend lacks DOM or JavaScript automation.
Examples
Verify that Windscribe changed the visible public address:
state = browser.get_ip_state() print(state["ip"], state.get("city"), state.get("timezone"))
- maximize_window(*, os_fallback: bool = True) Browser¶
Maximize the active visible browser window across supported engines.
Selenium uses WebDriver. Playwright Chromium first uses CDP window bounds; Firefox and Camoufox use page focus plus JavaScript sizing. When those mechanisms cannot confirm success, the optional desktop fallback sends the operating-system maximize shortcut through PyAutoGUI.
Parameters
Name
Type
Description
os_fallback
bool
Use a PyAutoGUI desktop shortcut after a native backend attempt fails.
Returns
Type
Description
This browser for fluent project code.
Raises
Exception
Description
If no supported maximization mechanism succeeds.
If the backend has no controlled page.
Examples
Maximize before coordinate-based interaction:
browser.maximize_window()
- bring_to_front() Browser¶
Activate the real browser window, including Camoufox on Windows.
Playwright’s page-level
bring_to_front()is not an operating-system focus guarantee. On Windows this method resolves and activates the HWND owned by the launched browser process.Returns
Type
Description
This browser for fluent project code.
Raises
Exception
Description
If the controlled browser window cannot be focused.
Examples
Focus before coordinate-based automation:
browser.bring_to_front()
- keep_in_front(duration: float | None = None) BrowserFocusLease¶
Focus the browser and keep its Windows window topmost temporarily.
This method is intended for PyAutoGUI workflows. It activates the controlled page first, then pins the resulting foreground window using the Windows API. A duration releases it automatically; omitting the duration returns an indefinite lease that the caller must close.
Parameters
Name
Type
Description
duration
float | None
Optional positive lease lifetime in seconds.
Returns
Type
Description
Closeable and context-manageable focus lease.
Raises
Exception
Description
If the active operating system cannot provide the required topmost-window guarantee.
If the browser cannot be focused or pinned.
ValueError
If
durationis not positive.Examples
Hold focus during a bounded PyAutoGUI sequence:
with browser.keep_in_front(duration=15): perform_visual_drag()
- refresh(*, timeout: float | None = None, wait_until: str = 'load') Browser¶
Reload the active page.
Parameters
Name
Type
Description
timeout
float | None
Optional navigation timeout in seconds.
wait_until
str
Playwright navigation completion state.
Returns
Type
Description
This browser.
Raises
Exception
Description
The backend has no DOM capability.
Examples
Reload and continue with the same facade:
browser.refresh().find("main")
- back(*, timeout: float | None = None) Browser¶
Navigate backward in page history.
Parameters
Name
Type
Description
timeout
float | None
Optional navigation timeout in seconds.
Returns
Type
Description
This browser.
Raises
Exception
Description
The backend has no DOM capability.
Examples
Return to a result list:
browser.back()
- forward(*, timeout: float | None = None) Browser¶
Navigate forward in page history.
Parameters
Name
Type
Description
timeout
float | None
Optional navigation timeout in seconds.
Returns
Type
Description
This browser.
Raises
Exception
Description
The backend has no DOM capability.
Examples
Revisit the next history entry:
browser.forward()
- stop() Browser¶
Stop the active document navigation without closing the session.
Returns
Type
Description
This browser.
Raises
Exception
Description
JavaScript is unavailable.
Examples
Stop a page that keeps loading nonessential resources:
browser.stop()
- javascript(script: str, *args: Any) Any¶
Execute one backend-neutral JavaScript function body.
The source uses Selenium-style
argumentsand may containreturn. Playwright wraps the same body in a function internally.Parameters
Name
Type
Description
script
str
JavaScript function body.
*args
Any
Serializable values or facade elements.
Returns
Type
Description
Any
Backend-serialized JavaScript result.
Raises
Exception
Description
JavaScript is unavailable.
Examples
Read the document readiness state identically on both technologies:
state = browser.javascript("return document.readyState")
- javascript_async(script: str, *args: Any, timeout: float | None = None) Any¶
Execute asynchronous JavaScript and return its resolved value.
Parameters
Name
Type
Description
script
str
JavaScript function body. Selenium receives a completion callback as the final
argumentsitem. Playwright may return a value or promise from the same body.*args
Any
Serializable values or facade elements.
timeout
float | None
Optional script deadline in seconds.
Returns
Type
Description
Any
Backend-serialized resolved JavaScript value.
Raises
Exception
Description
JavaScript is unavailable.
The script fails or exceeds its deadline.
Examples
Resolve a delayed value identically on both technologies:
value = browser.javascript_async( "setTimeout(() => arguments[1](arguments[0]), 10)", "ready", )
- save_as_pdf(path: str | Any | None = None, **options: Any) bytes | Any¶
Render the active page as PDF bytes or save them to disk.
Parameters
Name
Type
Description
path
str | Any | None
Optional destination path. Omit it to return PDF bytes.
**options
Any
Provider PDF/print options.
Returns
Type
Description
bytes | Any
PDF bytes when
pathis omitted, otherwise the absolute destinationPath.Raises
Exception
Description
The backend cannot print PDF.
Provider printing or file persistence fails.
Examples
Save the active page as a PDF:
destination = browser.save_as_pdf("reports/page.pdf")
- add_init_script(script: str | None = None, *, path: str | Any | None = None) None¶
Register JavaScript that runs before future page scripts.
Parameters
Name
Type
Description
script
str | None
JavaScript source text.
path
str | Any | None
UTF-8 JavaScript file path. Exactly one of
scriptorpathmust be supplied.Raises
Exception
Description
Both or neither source forms are supplied.
The backend cannot register init scripts.
Examples
Define a stable project marker before the next navigation:
browser.add_init_script("window.__project = '59-IN'")
- expose_function(name: str, callback: Any) CapabilityResult[Any]¶
Expose a Python callback to JavaScript when the backend supports it.
Parameters
Name
Type
Description
name
str
Global JavaScript function name.
callback
Any
Synchronous Python callable.
Returns
Type
Description
CapabilityResult[Any]
Supported result for Playwright-shaped backends, otherwise a structured negative result explaining the missing transport.
Examples
Expose a deterministic formatter to page JavaScript:
result = browser.expose_function("formatCase", format_case)
- screenshot(path: str | Any | None = None, *, full_page: bool = False, format: str | None = None) bytes | Any¶
Capture the active page as bytes or save it to disk.
Parameters
Name
Type
Description
path
str | Any | None
Optional destination path. Omit it to return bytes.
full_page
bool
Capture the complete scrollable document when supported.
format
str | None
Optional
pngorjpegoutput format.Returns
Type
Description
bytes | Any
Screenshot bytes or an absolute destination
Path.Raises
Exception
Description
The requested format is invalid.
The provider capture fails.
Examples
Save a full-page diagnostic image:
image = browser.screenshot("reports/page.png", full_page=True)
- save_page(path: str | Any, *, include_assets: bool = False) Any¶
Save the current document as HTML or a self-contained MHTML snapshot.
Parameters
Name
Type
Description
path
str | Any
Destination file path.
include_assets
bool
Capture MHTML with embedded reachable assets. This requires Chromium CDP; plain HTML works on every DOM backend.
Returns
Type
Description
Any
Absolute destination
Path.Raises
Exception
Description
Asset capture is requested without CDP.
Examples
Save plain diagnostic markup:
saved = browser.save_page("reports/page.html")
- print(**options: Any) CapabilityResult[Any]¶
Print the active page through the normalized PDF implementation.
Parameters
Name
Type
Description
**options
Any
PDF options. A
pathentry saves to disk; omitting it returns PDF bytes inside the result.Returns
Type
Description
CapabilityResult[Any]
Structured supported result containing bytes or a destination path, or a structured negative result when PDF is unavailable.
Examples
Soft-check printable PDF support:
result = browser.print(path="reports/page.pdf") if not result.supported: diagnostics.append(result.reason)
- find(tag: str | None = None, *, text: str | Pattern[str] | ValueMatch | None = None, attrs: Mapping[str, Any] | None = None, timeout: float | None = None, required: bool = False, **conditions: Any) BrowserElement | None | CapabilityResult[Any]¶
Find the first element using structured BeautifulSoup-like criteria.
Parameters
Name
Type
Description
tag
str | None
Optional tag name.
attrs
Mapping[str, Any] | None
Attribute criteria.
Truemeans attribute existence.text
str | Pattern[str] | ValueMatch | None
Visible-text criterion.
timeout
float | None
Positive seconds enable waiting; zero or
Noneperforms one immediate query.required
bool
Raise when DOM is unsupported or no element is found.
**conditions
Any
Search controls
match,case_sensitive,condition, andparentplus BeautifulSoup-style attribute conditions such asid="results"orclass_="active".Returns
Type
Description
BrowserElement | None | CapabilityResult[Any]
First matching element,
None, or structured unsupported result.Raises
Exception
Description
No match exists and
requiredis true.A positive timeout expires and
requiredis true.DOM is unavailable and
requiredis true.Examples
Find a visible case link by partial case-insensitive text:
link = browser.find( "a", text="case details", match="contains", case_sensitive=False, condition="visible", timeout=10, )
- find_all(tag: str | None = None, *, text: str | Pattern[str] | ValueMatch | None = None, attrs: Mapping[str, Any] | None = None, timeout: float | None = None, minimum: int | None = None, maximum: int | None = None, count: int | None = None, **conditions: Any) BrowserCollection | CapabilityResult[Any]¶
Find every element matching structured criteria in document order.
Parameters
Name
Type
Description
tag
str | None
Optional tag name.
attrs
Mapping[str, Any] | None
Attribute criteria.
text
str | Pattern[str] | ValueMatch | None
Visible-text criterion.
timeout
float | None
Positive seconds wait until cardinality constraints pass.
minimum
int | None
Optional minimum result count.
maximum
int | None
Optional maximum result count.
count
int | None
Optional exact result count, mutually exclusive with bounds.
**conditions
Any
Search controls and BeautifulSoup-style attributes.
Returns
Type
Description
Ordered browser collection or structured unsupported result.
Raises
Exception
Description
Required search remains empty.
Required positive wait expires.
DOM is unavailable and required.
Examples
Find every enabled result action:
buttons = browser.find_all( "button", attrs={"data-action": True}, condition="enabled" )
- select_one(css: str, *, timeout: float | None = None, required: bool = False, **conditions: Any) BrowserElement | None | CapabilityResult[Any]¶
Find the first element using an explicit CSS selector.
Parameters
Name
Type
Description
css
str
CSS selector.
timeout
float | None
Positive seconds enable waiting.
required
bool
Raise when unsupported or not found.
**conditions
Any
Optional
conditionandparentcontrols.Returns
Type
Description
BrowserElement | None | CapabilityResult[Any]
First matching element,
None, or unsupported result.Raises
Exception
Description
If unsupported conditions are passed.
Examples
Select one result row by CSS:
row = browser.select_one("table.results > tbody > tr", timeout=10)
- select(css: str, *, timeout: float | None = None, minimum: int | None = None, maximum: int | None = None, count: int | None = None, **conditions: Any) BrowserCollection | CapabilityResult[Any]¶
Find all elements using an explicit CSS selector.
Parameters
Name
Type
Description
css
str
CSS selector.
timeout
float | None
Positive seconds wait until cardinality constraints pass.
minimum
int | None
Optional minimum result count.
maximum
int | None
Optional maximum result count.
count
int | None
Optional exact result count.
**conditions
Any
Optional
condition,parent, andrequired.Returns
Type
Description
Ordered collection or unsupported result.
Raises
Exception
Description
If unsupported conditions are passed,
countis combined withminimumormaximum, a limit is negative, orminimumexceedsmaximum.Examples
Select every result row:
rows = browser.select("table.results > tbody > tr")
- xpath(expression: str, *, timeout: float | None = None, required: bool = False, **conditions: Any) BrowserElement | None | CapabilityResult[Any]¶
Find the first element using an explicit XPath expression.
Parameters
Name
Type
Description
expression
str
XPath expression.
timeout
float | None
Positive seconds enable waiting.
required
bool
Raise when unsupported or not found.
**conditions
Any
Optional
conditionandparentcontrols.Returns
Type
Description
BrowserElement | None | CapabilityResult[Any]
First matching element,
None, or unsupported result.Raises
Exception
Description
If unsupported conditions are passed.
Examples
Find an exact normalized label:
label = browser.xpath("//label[normalize-space(.)='Court']")
- xpath_all(expression: str, *, timeout: float | None = None, **conditions: Any) BrowserCollection | CapabilityResult[Any]¶
Find all elements using an explicit XPath expression.
Parameters
Name
Type
Description
expression
str
XPath expression.
timeout
float | None
Positive seconds wait until at least one result exists.
**conditions
Any
Optional
condition,parent, andrequired.Returns
Type
Description
Ordered collection or unsupported result.
Raises
Exception
Description
If unsupported conditions are passed.
Examples
Find all non-empty table rows:
rows = browser.xpath_all("//tbody/tr[td]")
- close() None¶
Close the owned browser session idempotently.
Examples
Close explicitly outside a context manager:
browser.close()
- class ddp_utils.browser.facade.browser.BrowserFocusLease(release: Callable[[], None], duration: float | None)¶
Bases:
objectOwn a temporary operating-system topmost-window request.
Parameters
Name
Type
Description
release
Callable[[], None]
Idempotent callback that removes the topmost state.
duration
float | None
Optional number of seconds before automatic release.
Examples
Keep the browser available to PyAutoGUI for ten seconds:
with browser.keep_in_front(duration=10): run_desktop_input()
Release an indefinite lease explicitly:
lease = browser.keep_in_front() lease.close()
Start an optional automatic-release timer.
Parameters
Name
Type
Description
release
Callable[[], None]
Idempotent operating-system release callback.
duration
float | None
Positive lifetime in seconds, or
Nonefor an indefinite lease.Raises
Exception
Description
ValueError
If
durationis not positive.Examples
BrowserFocusLease(release, 5.0)releases after five seconds.- property closed: bool¶
Return whether this lease has already released the window.
Returns
Trueafter explicit or timed release.Examples
if lease.closed: stop_desktop_input().
- close() None¶
Release the topmost state exactly once.
Examples
lease.close()may be called repeatedly without side effects.