# Chrome Extension for Browser Automation

Manifest V3 Chrome extension that executes browser automation commands received from the Swift server.

## 🎯 Features

- **Manifest V3 Compatible**: Uses modern Chrome extension architecture
- **Persistent Polling**: Stays responsive using `chrome.alarms` API
- **Dynamic API Execution**: Executes Chrome API calls from server commands
- **Page Interaction**: Uses Chrome Debugger API to run JavaScript in tabs
- **Server Registration**: Registers with server on startup

## 📋 Prerequisites

- Google Chrome or Chromium-based browser
- Developer mode enabled in Chrome

## 🛠️ Installation

See [INSTALL.md](INSTALL.md) for quick installation instructions.

## 📁 Extension Structure

```
chrome-extension/           # Located at project root
├── manifest.json           # Extension configuration
├── background_polling.js   # Service worker (main logic)
├── INSTALL.md             # Installation guide
└── README.md              # This file
```

## 🔧 How It Works

### 1. Service Worker Lifecycle

The extension uses a Manifest V3 service worker that:
- Wakes up every 3 seconds via `chrome.alarms`
- Polls the server for commands
- Goes back to sleep (Chrome shows it as "inactive")
- Wakes up again when the alarm fires

### 2. Command Execution Flow

```javascript
// 1. Poll server for commands
GET http://localhost:9876/poll

// 2. Receive command
{
  "id": "cmd_123",
  "command": "execute",
  "params": {
    "code": "chrome.tabs.create({ \"url\": \"https://example.com\" })"
  }
}

// 3. Execute Chrome API
chrome.tabs.create({ "url": "https://example.com" })

// 4. Send result back
POST http://localhost:9876/response
{
  "id": "cmd_123",
  "success": true,
  "result": { "id": 456, "url": "https://example.com" }
}
```

### 3. Special Handling for Page Interaction

For `chrome.scripting.executeScript`, the extension uses the Chrome Debugger API:

```javascript
// User command
chrome.scripting.executeScript({
  "target": { "tabId": 123 },
  "code": "document.title"
})

// Extension converts to:
chrome.debugger.attach({ tabId: 123 }, "1.3")
chrome.debugger.sendCommand({ tabId: 123 }, "Runtime.evaluate", {
  expression: "document.title",
  returnByValue: true
})
```

## ⚙️ Configuration

### manifest.json

Key permissions required:
```json
{
  "permissions": [
    "tabs",          // Tab management
    "debugger",      // Page interaction
    "scripting",     // Script injection
    "storage",       // Data storage
    "history",       // History access
    "windows",       // Window control
    "bookmarks",     // Bookmark management
    "alarms"         // Service worker wake-up
  ],
  "host_permissions": [
    "<all_urls>",    // Access all websites
    "http://localhost:9876/*"  // Server communication
  ]
}
```

### background_polling.js

Key configuration:
```javascript
const PORT = 9876;  // Server port
chrome.alarms.create('pollCommands', { 
  periodInMinutes: 0.05  // Poll every 3 seconds
});
```

## 🔌 Chrome APIs Tested

The following Chrome APIs have been tested and confirmed working:

- `chrome.tabs.create()` - Create new tabs
- `chrome.tabs.query()` - Query existing tabs  
- `chrome.tabs.remove()` - Close tabs
- `chrome.scripting.executeScript()` - Execute JavaScript in tabs (via debugger API)
- `chrome.windows.getCurrent()` - Get current window info

Other Chrome APIs should work but haven't been tested:
- `chrome.bookmarks.*` - Bookmark operations
- `chrome.history.*` - Browsing history
- `chrome.storage.*` - Extension storage
- And others with proper permissions in manifest.json

## 🐛 Debugging

### View Service Worker Console

1. Go to `chrome://extensions/`
2. Find "Sonatic Browser Control (Alpha)"
3. Click "service worker" link
4. Console will show all logs and errors

### Common Issues

**Service Worker Shows "Inactive"**
- This is normal! The alarm wakes it up every 3 seconds

**No Connection to Server**
- Check server is running: `lsof -i :9876`
- Check console for connection errors
- Reload the extension

**Commands Not Executing**
- Check service worker console for errors
- Verify JSON syntax in command files
- Ensure tab IDs are valid

## 🔒 Security Considerations

- Extension has broad permissions to enable automation
- Configured to only connect to localhost:9876
- Commands are executed with the permissions granted in manifest.json
- Recommended for development/testing environments only

## 🔄 Manifest V3 Limitations & Solutions

| Limitation | Our Solution |
|------------|--------------|
| Service workers shut down after ~30s | Use `chrome.alarms` to wake up |
| No persistent background pages | Store state in command queue on server |
| Can't use `eval()` or inline scripts | Parse JSON arguments safely |
| CSP restrictions | Use Chrome Debugger API for page scripts |

## 🤝 Contributing

Key areas for improvement:

- `background_polling.js` - Main service worker logic
- Add more robust error handling
- Optimize polling frequency
- Add command batching support

## 📄 License

MIT