# 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](https://www.w3schools.com/jsref/met_console_assert.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/assert) * `clear()`: Clears the console. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_clear.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/clear) * `count(label: str = 'default')`: Logs the number of times this particular call to count() has been called. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_count.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/count) * `error(*args)`: Outputs an error message to the console. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_error.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/error) * `group(*args)`: Creates a new inline group in the console. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_group.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/group) * `groupCollapsed(*args)`: Creates a new inline group in the console that is initially collapsed. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_groupcollapsed.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/groupCollapsed) * `groupEnd()`: Exits the current inline group in the console. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_groupend.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/groupEnd) * `info(*args)`: Outputs an informational message to the console. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_info.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/info) * `log(*args)`: Outputs a message to the console. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_log.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/log) * `table(data)`: Displays tabular data as a table. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_table.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/table) * `time(label: str = 'default')`: Starts a timer you can use to track how long an operation takes. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_time.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/time) * `timeEnd(label: str = 'default')`: Stops a timer that was previously started by console.time(). [W3Schools Reference](https://www.w3schools.com/jsref/met_console_timeend.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/timeEnd) * `trace(*args)`: Outputs a stack trace to the console. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_trace.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/trace) * `warn(*args)`: Outputs a warning message to the console. [W3Schools Reference](https://www.w3schools.com/jsref/met_console_warn.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/console/warn) ### Usage Examples ```python 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](https://www.w3schools.com/jsref/prop_his_length.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/History/length) ### Methods * `back()`: Loads the previous URL (page) in the history list. [W3Schools Reference](https://www.w3schools.com/jsref/met_his_back.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/History/back) * `forward()`: Loads the next URL (page) in the history list. [W3Schools Reference](https://www.w3schools.com/jsref/met_his_forward.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/History/forward) * `go(number: int)`: Loads a specific URL (page) from the history list. [W3Schools Reference](https://www.w3schools.com/jsref/met_his_go.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/History/go) ### Usage Examples ```python 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](https://www.w3schools.com/jsref/prop_loc_hash.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/hash) * `host -> str`: Sets or returns the hostname and port number of a URL. [W3Schools Reference](https://www.w3schools.com/jsref/prop_loc_host.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/host) * `hostname -> str`: Sets or returns the hostname of a URL. [W3Schools Reference](https://www.w3schools.com/jsref/prop_loc_hostname.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/hostname) * `href -> str`: Sets or returns the entire URL. [W3Schools Reference](https://www.w3schools.com/jsref/prop_loc_href.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/href) * `origin -> str`: Returns the protocol, hostname and port number of a URL. [W3Schools Reference](https://www.w3schools.com/jsref/prop_loc_origin.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/origin) * `pathname -> str`: Sets or returns the path name of a URL. [W3Schools Reference](https://www.w3schools.com/jsref/prop_loc_pathname.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/pathname) * `port -> str`: Sets or returns the port number of a URL. [W3Schools Reference](https://www.w3schools.com/jsref/prop_loc_port.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/port) * `protocol -> str`: Sets or returns the protocol of a URL. [W3Schools Reference](https://www.w3schools.com/jsref/prop_loc_protocol.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/protocol) * `search -> str`: Sets or returns the querystring part of a URL. [W3Schools Reference](https://www.w3schools.com/jsref/prop_loc_search.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/search) ### Methods * `assign(url: str)`: Loads a new document. [W3Schools Reference](https://www.w3schools.com/jsref/met_loc_assign.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/assign) * `reload(force_reload: bool = False)`: Reloads the current document. [W3Schools Reference](https://www.w3schools.com/jsref/met_loc_reload.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/reload) * `replace(url: str)`: Replaces the current document with a new one. [W3Schools Reference](https://www.w3schools.com/jsref/met_loc_replace.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Location/replace) ### Usage Examples ```python def main(ui): location = ui.htmlwindow.location # Display current URL information url_info = ui.document.getElementById("urlInfo") url_info.innerHTML = f"""

Current URL Information

Full URL: {location.href}

Protocol: {location.protocol}

Host: {location.host}

Pathname: {location.pathname}

Search: {location.search}

Hash: {location.hash}

""" # 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](https://www.w3schools.com/jsref/prop_nav_appcodename.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/appCodeName) * `appName -> str`: Returns the application name of the browser. [W3Schools Reference](https://www.w3schools.com/jsref/prop_nav_appname.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/appName) * `appVersion -> str`: Returns the version information of the browser. [W3Schools Reference](https://www.w3schools.com/jsref/prop_nav_appversion.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/appVersion) * `cookieEnabled -> bool`: Returns true if browser cookies are enabled. [W3Schools Reference](https://www.w3schools.com/jsref/prop_nav_cookieenabled.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/cookieEnabled) * `geolocation`: Returns a geolocation object that can be used to locate the user's position. [W3Schools Reference](https://www.w3schools.com/jsref/prop_nav_geolocation.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/geolocation) * `language -> str`: Returns the browser's language. [W3Schools Reference](https://www.w3schools.com/jsref/prop_nav_language.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language) * `onLine -> bool`: Returns true if the browser is online. [W3Schools Reference](https://www.w3schools.com/jsref/prop_nav_online.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine) * `platform -> str`: Returns the platform of the browser. [W3Schools Reference](https://www.w3schools.com/jsref/prop_nav_platform.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/platform) * `product -> str`: Returns the product name of the browser. [W3Schools Reference](https://www.w3schools.com/jsref/prop_nav_product.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/product) * `userAgent -> str`: Returns the user-agent header sent by the browser to the server. [W3Schools Reference](https://www.w3schools.com/jsref/prop_nav_useragent.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/userAgent) ### Methods * `javaEnabled() -> bool`: Returns whether Java is enabled in the browser. [W3Schools Reference](https://www.w3schools.com/jsref/met_nav_javaenabled.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/javaEnabled) ### Usage Examples ```python def main(ui): navigator = ui.htmlwindow.navigator # Display browser information browser_info = ui.document.getElementById("browserInfo") browser_info.innerHTML = f"""

Browser Information

Browser Name: {navigator.appName}

Browser Version: {navigator.appVersion}

User Agent: {navigator.userAgent}

Platform: {navigator.platform}

Language: {navigator.language}

Cookies Enabled: {'Yes' if navigator.cookieEnabled else 'No'}

Online: {'Yes' if navigator.onLine else 'No'}

Java Enabled: {'Yes' if navigator.javaEnabled() else 'No'}

""" # 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](https://www.w3schools.com/jsref/prop_screen_availheight.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Screen/availHeight) * `availWidth -> int`: Returns the width of the screen (excluding the Windows Taskbar). [W3Schools Reference](https://www.w3schools.com/jsref/prop_screen_availwidth.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Screen/availWidth) * `colorDepth -> int`: Returns the bit depth of the color palette for displaying images. [W3Schools Reference](https://www.w3schools.com/jsref/prop_screen_colordepth.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Screen/colorDepth) * `height -> int`: Returns the total height of the screen. [W3Schools Reference](https://www.w3schools.com/jsref/prop_screen_height.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Screen/height) * `pixelDepth -> int`: Returns the color resolution (in bits per pixel) of the screen. [W3Schools Reference](https://www.w3schools.com/jsref/prop_screen_pixeldepth.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Screen/pixelDepth) * `width -> int`: Returns the total width of the screen. [W3Schools Reference](https://www.w3schools.com/jsref/prop_screen_width.asp) | [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Screen/width) ### Usage Examples ```python def main(ui): screen = ui.htmlwindow.screen # Display screen information screen_info = ui.document.getElementById("screenInfo") screen_info.innerHTML = f"""

Screen Information

Total Size: {screen.width} x {screen.height}

Available Size: {screen.availWidth} x {screen.availHeight}

Color Depth: {screen.colorDepth} bits

Pixel Depth: {screen.pixelDepth} bits

""" # 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: ```python 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"""

Browser Information

Name: {navigator.appName}

Version: {navigator.appVersion}

Platform: {navigator.platform}

Language: {navigator.language}

Online: {'Yes' if navigator.onLine else 'No'}

Screen Information

Resolution: {screen.width} x {screen.height}

Available: {screen.availWidth} x {screen.availHeight}

Color Depth: {screen.colorDepth} bits

Current Page

URL: {location.href}

Protocol: {location.protocol}

Host: {location.host}

History Length: {history.length}

""" 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 += "
  • Cookies supported
  • " if navigator.javaEnabled(): console.info("Java is enabled") features_list.innerHTML += "
  • Java supported
  • " 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 - **[HTMLWindow](HTMLWindow)**: The parent object that contains these browser objects - **[Global Functions](Global-Functions)**: Main PyPositron functions - **[Document](Document)**: DOM manipulation