Positron

JavaScript Support

Understanding JavaScript execution in Positron through PythonMonkey

JavaScript Support

Positron provides full JavaScript support through real browser engines via pywebview.

Installation

JavaScript support is built-in when you install pywebview:

pip install pywebview

Or using requirements.txt:

pip install -r requirements.txt

pywebview gives you FULL modern JavaScript support - ES6+, modules, async/await, everything!

How JavaScript Works in Positron

Architecture

┌─────────────────────────────────┐
│     React App (JavaScript)      │
│  - Full React with hooks        │
│  - Modern JavaScript (ES6+)     │
│  - State management             │
│  - Event handlers               │
└────────────┬────────────────────┘

             │ Executed by

┌────────────▼────────────────────┐
│   Real Browser Engine           │
│  - V8 (Windows via WebView2)    │
│  - JavaScriptCore (macOS)       │
│  - WebKit (Linux)               │
│  - Full DOM APIs                │
│  - Modern web standards         │
└────────────┬────────────────────┘

             │ Renders to

┌────────────▼────────────────────┐
│   Native WebView                │
│  - HTML5/CSS3 display           │
│  - GPU acceleration             │
│  - Native scrolling             │
└─────────────────────────────────┘

What's Supported

Fully Supported

React and all modern frameworks - Vue, Angular, Svelte, etc. ✅ Modern JavaScript (ES6+) - Arrow functions, async/await, classes, modules ✅ ES Modules - Import/export, dynamic imports ✅ Full DOM API - querySelector, addEventListener, everything ✅ Event handlers - All DOM events work ✅ React hooks - useState, useEffect, useContext, custom hooks ✅ Component lifecycle - All React lifecycle methods ✅ Browser APIs - Fetch, LocalStorage, SessionStorage, WebSockets ✅ Console API - console.log, error, warn, etc. ✅ Modern CSS - Grid, Flexbox, animations, transforms ✅ HTML5 - All modern HTML elements

Platform-Specific

Some features depend on the underlying browser engine:

  • WebGL: Available on Windows (WebView2), check macOS/Linux
  • WebRTC: Supported on Windows/macOS, check Linux
  • Service Workers: Platform-dependent
  • WebAssembly: Supported on modern engines

React Integration

React works perfectly with Positron because:

  1. Real browser engine executes React

    • Vite dev server works out of the box
    • All JSX is compiled and executed natively
    • Hot module replacement works
    • No special configuration needed
  2. Native rendering

    • React manipulates the real DOM
    • Browser engine renders with GPU acceleration
    • Full React DevTools support (platform-dependent)
    • Updates happen reactively at native speed

Example: React Component

// This works perfectly in Positron
import { useState } from 'react'

function Counter() {
  const [count, setCount] = useState(0)
  
  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  )
}

This is real React running in a real browser engine - exactly like it would in Chrome or Safari!

Using JavaScript with IPC

You can call Python from JavaScript and vice versa:

From React to Python

// React component
function App() {
  const callPython = async () => {
    // This JavaScript runs via PythonMonkey
    const result = await window.ipcRenderer.invoke('python-function', 'data')
    console.log(result)
  }
  
  return <button onClick={callPython}>Call Python</button>
}

From Python to React

# Python main.py
from positron.ipc import ipc_main

@ipc_main.handle('python-function')
def handle_request(event, data):
    # Process in Python (full Python ecosystem)
    result = process_data(data)
    return result

Console Output

JavaScript console output appears in the Python terminal:

console.log('Hello from React!')  // Shows in terminal
console.error('Error message')     // Shows in terminal
console.warn('Warning')            // Shows in terminal

Performance Considerations

What PythonMonkey Does Well

  • ✅ Modern JavaScript syntax
  • ✅ React components and hooks
  • ✅ DOM manipulation
  • ✅ Event handling
  • ✅ State updates

Performance Tips

1. Use IPC for heavy operations

// Instead of processing in JavaScript
const data = await fetch('/api/data')
const processed = expensiveOperation(data)

// Do this in Python via IPC
const processed = await window.ipcRenderer.invoke('process-data')

2. Keep rendering logic in React

  • React is optimized for UI updates
  • Let React handle component rendering
  • Use Python for backend logic

3. Minimize JavaScript complexity

  • Complex algorithms → Python
  • UI logic → React/JavaScript
  • Data processing → Python

Debugging JavaScript

Console Logging

console.log('Debug:', variable)
console.error('Error occurred:', error)
console.table(arrayData)  // May have limited support

Error Handling

try {
  // JavaScript code
  const result = await window.ipcRenderer.invoke('might-fail')
} catch (error) {
  console.error('IPC Error:', error.message)
}

Python Side Debugging

@ipc_main.handle('debug-endpoint')
def debug(event, data):
    print(f"Received from JS: {data}")
    import pdb; pdb.set_trace()  # Python debugger
    return "response"

Browser API Compatibility

Available in Positron

APIStatusNotes
console.*✅ FullAll console methods work
window.ipcRenderer✅ FullCustom Positron API
document.querySelector✅ FullDOM selection
element.addEventListener✅ FullEvent handling
setTimeout/setInterval✅ FullTimers work
JSON.*✅ FullJSON parsing
localStorage⚠️ PartialLimited support
fetch⚠️ PartialUse IPC instead
XMLHttpRequest⚠️ PartialUse IPC instead

Not Available

APIAlternative
fetchUse Python's requests via IPC
Service WorkersNot supported
WebGLNot supported
WebRTCNot supported
WebSocketsUse Python's websockets via IPC

Best Practices

1. Use React for UI, Python for Logic

// ✅ Good: UI in React
function DataDisplay({ data }) {
  return (
    <div>
      {data.map(item => <Card key={item.id} item={item} />)}
    </div>
  )
}
# ✅ Good: Heavy processing in Python
@ipc_main.handle('process-data')
def process_data(event, raw_data):
    import pandas as pd
    df = pd.DataFrame(raw_data)
    processed = df.groupby('category').sum()
    return processed.to_dict('records')

2. Handle Network Requests in Python

// ❌ Avoid: Fetch in JavaScript
const data = await fetch('https://api.example.com/data')

// ✅ Better: Fetch in Python via IPC
const data = await window.ipcRenderer.invoke('fetch-data', url)
# Python handles the request
import requests

@ipc_main.handle('fetch-data')
def fetch_data(event, url):
    response = requests.get(url)
    return response.json()

3. Use TypeScript for Better Development

// TypeScript provides type safety
interface IPCRenderer {
  send(channel: string, ...args: any[]): void
  invoke(channel: string, ...args: any[]): Promise<any>
  on(channel: string, callback: Function): void
}

declare global {
  interface Window {
    ipcRenderer: IPCRenderer
  }
}

Verifying JavaScript Support

Test that pywebview is installed:

python -c "import webview; print('✓ JavaScript support available via pywebview')"

Run a simple test:

from positron import App, BrowserWindow

app = App()

def test_js():
    win = BrowserWindow()
    win.load_html("""
    <html>
      <head>
        <script>
          console.log('JavaScript is working!')
          setTimeout(() => {
            document.body.innerHTML = '<h1>JavaScript Works!</h1>'
          }, 100)
        </script>
      </head>
      <body>Loading...</body>
    </html>
    """)

app.when_ready(test_js)
app.run()

You should see:

  1. "JavaScript is working!" in terminal
  2. "JavaScript Works!" displayed in window

Troubleshooting

JavaScript Not Executing

Check installation:

pip list | grep -i pywebview

Should show: pywebview

Reinstall if missing:

pip install pywebview --force-reinstall

React App Not Rendering

  1. Check browser console (terminal output)
  2. Verify Vite build is working
  3. Check for JavaScript errors in terminal
  4. Test with simple HTML first

Performance Issues

  1. Profile where time is spent:

    • React rendering? → Optimize components
    • Python processing? → Optimize algorithms
    • IPC communication? → Batch requests
  2. Use React DevTools mindset:

    • Memoize expensive computations
    • Use React.memo for components
    • Implement proper key props

Summary

Positron provides FULL JavaScript support for modern React apps through pywebview and real browser engines!

What you get:

  • ✅ Real React with all features
  • ✅ Modern JavaScript (ES6+, modules, async/await)
  • ✅ HTML5 and CSS3
  • ✅ Vite dev server works perfectly
  • ✅ Hot module replacement
  • ✅ All browser APIs (Fetch, WebSockets, etc.)

Installation: pip install pywebview

Best practice: Build amazing UIs in React, powerful backends in Python

The combination of React's UI capabilities and Python's backend power makes Positron perfect for:

  • Data science dashboards - Pandas/NumPy backend, React frontend
  • Machine learning tools - TensorFlow/PyTorch with modern UI
  • Automation interfaces - Python automation with beautiful web UI
  • Internal tools - Enterprise apps with Python + React
  • Desktop applications - Native-feeling apps with web technologies

On this page