Browser Objects
PyPositron provides access to several browser objects that give you information about the browser environment, navigation history, screen properties, and more. These objects are accessed through the ui.htmlwindow
object and provide the same functionality as their JavaScript counterparts.
Console
The Console object provides access to the browser's debugging console. It's useful for logging, debugging, and outputting information during development.
Properties
The Console object primarily consists of methods rather than properties.
Methods
assert(assertion: bool, *args)
: Writes an error message to the console if the assertion is false. W3Schools Reference | MDN Referenceclear()
: Clears the console. W3Schools Reference | MDN Referencecount(label: str = 'default')
: Logs the number of times this particular call to count() has been called. W3Schools Reference | MDN Referenceerror(*args)
: Outputs an error message to the console. W3Schools Reference | MDN Referencegroup(*args)
: Creates a new inline group in the console. W3Schools Reference | MDN ReferencegroupCollapsed(*args)
: Creates a new inline group in the console that is initially collapsed. W3Schools Reference | MDN ReferencegroupEnd()
: Exits the current inline group in the console. W3Schools Reference | MDN Referenceinfo(*args)
: Outputs an informational message to the console. W3Schools Reference | MDN Referencelog(*args)
: Outputs a message to the console. W3Schools Reference | MDN Referencetable(data)
: Displays tabular data as a table. W3Schools Reference | MDN Referencetime(label: str = 'default')
: Starts a timer you can use to track how long an operation takes. W3Schools Reference | MDN ReferencetimeEnd(label: str = 'default')
: Stops a timer that was previously started by console.time(). W3Schools Reference | MDN Referencetrace(*args)
: Outputs a stack trace to the console. W3Schools Reference | MDN Referencewarn(*args)
: Outputs a warning message to the console. W3Schools Reference | MDN Reference
Usage Examples
def main(ui):
console = ui.htmlwindow.console
# Basic logging
console.log("Application started")
console.info("This is informational")
console.warn("This is a warning")
console.error("This is an error")
# Grouped logging
console.group("User Actions")
console.log("User clicked button")
console.log("User entered text")
console.groupEnd()
# Timing operations
console.time("data-processing")
# ... some operation
console.timeEnd("data-processing")
# Counting
for i in range(5):
console.count("loop-iteration")
# Clear console
console.clear()
History
The History object contains the URLs visited by the user (within a browser window). It provides methods to navigate through the browser history.
Properties
length -> int
: Returns the number of URLs (pages) in the history list. W3Schools Reference | MDN Reference
Methods
back()
: Loads the previous URL (page) in the history list. W3Schools Reference | MDN Referenceforward()
: Loads the next URL (page) in the history list. W3Schools Reference | MDN Referencego(number: int)
: Loads a specific URL (page) from the history list. W3Schools Reference | MDN Reference
Usage Examples
def main(ui):
history = ui.htmlwindow.history
# Navigation buttons
back_btn = ui.document.getElementById("backBtn")
forward_btn = ui.document.getElementById("forwardBtn")
def go_back():
if history.length > 1:
history.back()
def go_forward():
history.forward()
back_btn.addEventListener("click", go_back)
forward_btn.addEventListener("click", go_forward)
# Display history length
history_info = ui.document.getElementById("historyInfo")
history_info.innerText = f"History has {history.length} entries"
Location
The Location object contains information about the current URL and provides methods to navigate to different URLs.
Properties
hash -> str
: Sets or returns the anchor part (#) of a URL. W3Schools Reference | MDN Referencehost -> str
: Sets or returns the hostname and port number of a URL. W3Schools Reference | MDN Referencehostname -> str
: Sets or returns the hostname of a URL. W3Schools Reference | MDN Referencehref -> str
: Sets or returns the entire URL. W3Schools Reference | MDN Referenceorigin -> str
: Returns the protocol, hostname and port number of a URL. W3Schools Reference | MDN Referencepathname -> str
: Sets or returns the path name of a URL. W3Schools Reference | MDN Referenceport -> str
: Sets or returns the port number of a URL. W3Schools Reference | MDN Referenceprotocol -> str
: Sets or returns the protocol of a URL. W3Schools Reference | MDN Referencesearch -> str
: Sets or returns the querystring part of a URL. W3Schools Reference | MDN Reference
Methods
assign(url: str)
: Loads a new document. W3Schools Reference | MDN Referencereload(force_reload: bool = False)
: Reloads the current document. W3Schools Reference | MDN Referencereplace(url: str)
: Replaces the current document with a new one. W3Schools Reference | MDN Reference
Usage Examples
def main(ui):
location = ui.htmlwindow.location
# Display current URL information
url_info = ui.document.getElementById("urlInfo")
url_info.innerHTML = f"""
<h3>Current URL Information</h3>
<p><strong>Full URL:</strong> {location.href}</p>
<p><strong>Protocol:</strong> {location.protocol}</p>
<p><strong>Host:</strong> {location.host}</p>
<p><strong>Pathname:</strong> {location.pathname}</p>
<p><strong>Search:</strong> {location.search}</p>
<p><strong>Hash:</strong> {location.hash}</p>
"""
# Navigation functions
def navigate_to_page(url):
location.assign(url)
def reload_page():
if ui.htmlwindow.confirm("Reload the page?"):
location.reload()
# URL manipulation
def change_hash(new_hash):
location.hash = new_hash
# Set up navigation buttons
reload_btn = ui.document.getElementById("reloadBtn")
if reload_btn:
reload_btn.addEventListener("click", reload_page)
Navigator
The Navigator object contains information about the browser and the user's environment.
Properties
appCodeName -> str
: Returns the application code name of the browser. W3Schools Reference | MDN ReferenceappName -> str
: Returns the application name of the browser. W3Schools Reference | MDN ReferenceappVersion -> str
: Returns the version information of the browser. W3Schools Reference | MDN ReferencecookieEnabled -> bool
: Returns true if browser cookies are enabled. W3Schools Reference | MDN Referencegeolocation
: Returns a geolocation object that can be used to locate the user's position. W3Schools Reference | MDN Referencelanguage -> str
: Returns the browser's language. W3Schools Reference | MDN ReferenceonLine -> bool
: Returns true if the browser is online. W3Schools Reference | MDN Referenceplatform -> str
: Returns the platform of the browser. W3Schools Reference | MDN Referenceproduct -> str
: Returns the product name of the browser. W3Schools Reference | MDN ReferenceuserAgent -> str
: Returns the user-agent header sent by the browser to the server. W3Schools Reference | MDN Reference
Methods
javaEnabled() -> bool
: Returns whether Java is enabled in the browser. W3Schools Reference | MDN Reference
Usage Examples
def main(ui):
navigator = ui.htmlwindow.navigator
# Display browser information
browser_info = ui.document.getElementById("browserInfo")
browser_info.innerHTML = f"""
<h3>Browser Information</h3>
<p><strong>Browser Name:</strong> {navigator.appName}</p>
<p><strong>Browser Version:</strong> {navigator.appVersion}</p>
<p><strong>User Agent:</strong> {navigator.userAgent}</p>
<p><strong>Platform:</strong> {navigator.platform}</p>
<p><strong>Language:</strong> {navigator.language}</p>
<p><strong>Cookies Enabled:</strong> {'Yes' if navigator.cookieEnabled else 'No'}</p>
<p><strong>Online:</strong> {'Yes' if navigator.onLine else 'No'}</p>
<p><strong>Java Enabled:</strong> {'Yes' if navigator.javaEnabled() else 'No'}</p>
"""
# Feature detection
def check_features():
features = []
if navigator.cookieEnabled:
features.append("Cookies")
if navigator.javaEnabled():
features.append("Java")
if hasattr(navigator, 'geolocation'):
features.append("Geolocation")
return features
# Online/offline detection
def update_connection_status():
status_element = ui.document.getElementById("connectionStatus")
if navigator.onLine:
status_element.innerText = "Online"
status_element.style.color = "green"
else:
status_element.innerText = "Offline"
status_element.style.color = "red"
# Monitor online/offline events
ui.htmlwindow.addEventListener("online", update_connection_status)
ui.htmlwindow.addEventListener("offline", update_connection_status)
update_connection_status()
Screen
The Screen object contains information about the user's screen and display.
Properties
availHeight -> int
: Returns the height of the screen (excluding the Windows Taskbar). W3Schools Reference | MDN ReferenceavailWidth -> int
: Returns the width of the screen (excluding the Windows Taskbar). W3Schools Reference | MDN ReferencecolorDepth -> int
: Returns the bit depth of the color palette for displaying images. W3Schools Reference | MDN Referenceheight -> int
: Returns the total height of the screen. W3Schools Reference | MDN ReferencepixelDepth -> int
: Returns the color resolution (in bits per pixel) of the screen. W3Schools Reference | MDN Referencewidth -> int
: Returns the total width of the screen. W3Schools Reference | MDN Reference
Usage Examples
def main(ui):
screen = ui.htmlwindow.screen
# Display screen information
screen_info = ui.document.getElementById("screenInfo")
screen_info.innerHTML = f"""
<h3>Screen Information</h3>
<p><strong>Total Size:</strong> {screen.width} x {screen.height}</p>
<p><strong>Available Size:</strong> {screen.availWidth} x {screen.availHeight}</p>
<p><strong>Color Depth:</strong> {screen.colorDepth} bits</p>
<p><strong>Pixel Depth:</strong> {screen.pixelDepth} bits</p>
"""
# Responsive design based on screen size
def adjust_layout():
if screen.width < 1024:
# Small screen layout
ui.document.body.className = "small-screen"
elif screen.width < 1920:
# Medium screen layout
ui.document.body.className = "medium-screen"
else:
# Large screen layout
ui.document.body.className = "large-screen"
adjust_layout()
# Center window on screen
def center_window():
window_width = ui.htmlwindow.outerWidth
window_height = ui.htmlwindow.outerHeight
x = (screen.availWidth - window_width) // 2
y = (screen.availHeight - window_height) // 2
ui.htmlwindow.moveTo(x, y)
center_btn = ui.document.getElementById("centerBtn")
if center_btn:
center_btn.addEventListener("click", center_window)
Complete Usage Example
Here's a comprehensive example that uses all the browser objects together:
import py_positron
def main(ui):
# Get references to all browser objects
console = ui.htmlwindow.console
history = ui.htmlwindow.history
location = ui.htmlwindow.location
navigator = ui.htmlwindow.navigator
screen = ui.htmlwindow.screen
console.log("Application initialized")
# Create a system information display
def update_system_info():
info_container = ui.document.getElementById("systemInfo")
info_html = f"""
<div class="info-section">
<h3>Browser Information</h3>
<p>Name: {navigator.appName}</p>
<p>Version: {navigator.appVersion}</p>
<p>Platform: {navigator.platform}</p>
<p>Language: {navigator.language}</p>
<p>Online: {'Yes' if navigator.onLine else 'No'}</p>
</div>
<div class="info-section">
<h3>Screen Information</h3>
<p>Resolution: {screen.width} x {screen.height}</p>
<p>Available: {screen.availWidth} x {screen.availHeight}</p>
<p>Color Depth: {screen.colorDepth} bits</p>
</div>
<div class="info-section">
<h3>Current Page</h3>
<p>URL: {location.href}</p>
<p>Protocol: {location.protocol}</p>
<p>Host: {location.host}</p>
<p>History Length: {history.length}</p>
</div>
"""
info_container.innerHTML = info_html
console.log("System information updated")
# Navigation controls
def setup_navigation():
# Back/Forward buttons
back_btn = ui.document.getElementById("backBtn")
forward_btn = ui.document.getElementById("forwardBtn")
reload_btn = ui.document.getElementById("reloadBtn")
if back_btn:
back_btn.addEventListener("click", lambda: history.back())
if forward_btn:
forward_btn.addEventListener("click", lambda: history.forward())
if reload_btn:
reload_btn.addEventListener("click", lambda: location.reload())
# Feature detection and adaptive UI
def setup_adaptive_features():
features_list = ui.document.getElementById("features")
if navigator.cookieEnabled:
console.info("Cookies are enabled")
features_list.innerHTML += "<li>Cookies supported</li>"
if navigator.javaEnabled():
console.info("Java is enabled")
features_list.innerHTML += "<li>Java supported</li>"
else:
console.warn("Java is not enabled")
# Adjust UI based on screen size
if screen.width < 768:
ui.document.body.classList.add("mobile-layout")
console.log("Mobile layout applied")
else:
ui.document.body.classList.add("desktop-layout")
console.log("Desktop layout applied")
# Online/offline handling
def handle_connectivity():
def on_online():
console.log("Application is online")
status = ui.document.getElementById("connectionStatus")
if status:
status.innerText = "Online"
status.className = "status-online"
def on_offline():
console.warn("Application is offline")
status = ui.document.getElementById("connectionStatus")
if status:
status.innerText = "Offline"
status.className = "status-offline"
ui.htmlwindow.addEventListener("online", on_online)
ui.htmlwindow.addEventListener("offline", on_offline)
# Initial status
if navigator.onLine:
on_online()
else:
on_offline()
# Console logging demo
def demo_console_features():
console.group("Console Demo")
console.log("This is a normal log message")
console.info("This is an info message")
console.warn("This is a warning message")
console.error("This is an error message")
console.time("demo-timer")
# Simulate some work
for i in range(3):
console.count("demo-counter")
console.timeEnd("demo-timer")
console.groupEnd()
# Demo button
demo_btn = ui.document.getElementById("consoleDemo")
if demo_btn:
demo_btn.addEventListener("click", lambda: console.table([
{"Name": "PyPositron", "Type": "Framework", "Language": "Python"},
{"Name": "Webview", "Type": "Component", "Language": "JavaScript"},
{"Name": "HTML", "Type": "Markup", "Language": "HTML"}
]))
# Initialize all features
update_system_info()
setup_navigation()
setup_adaptive_features()
handle_connectivity()
demo_console_features()
# Refresh button
refresh_btn = ui.document.getElementById("refreshBtn")
if refresh_btn:
refresh_btn.addEventListener("click", update_system_info)
py_positron.openUI(
"browser-objects-demo.html",
main=main,
title="Browser Objects Demo",
width=900,
height=700,
debug=True
)
Best Practices
-
Feature Detection: Always check if features are available before using them.
-
Error Handling: Wrap browser object operations in try-catch blocks as some features may not be available.
-
Performance: Cache browser object references if you use them frequently.
-
Responsive Design: Use screen properties to create adaptive layouts.
-
Debugging: Make good use of the Console object for debugging and logging.
-
Connectivity: Monitor online/offline status for web-dependent features.
Related Documentation
- HTMLWindow: The parent object that contains these browser objects
- Global Functions: Main PyPositron functions
- Document: DOM manipulation