PyPositron Docs

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

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

Methods

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

Methods

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

Methods

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

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

  1. Feature Detection: Always check if features are available before using them.

  2. Error Handling: Wrap browser object operations in try-catch blocks as some features may not be available.

  3. Performance: Cache browser object references if you use them frequently.

  4. Responsive Design: Use screen properties to create adaptive layouts.

  5. Debugging: Make good use of the Console object for debugging and logging.

  6. Connectivity: Monitor online/offline status for web-dependent features.

Related Documentation