Back to the catalog

Contents

Bundle OKF 0.2 · 1 conceitos · faranahmadk/native-messaging

Open source Repository Open in the app JSON README (API)

About

# Contents

* [Chrome Native Messaging with OpenCode](chrome-native-messaging-opencode.md)

Details

Kind
OKF bundles
Topic
Communication
Publisher
faranahmadk
Origin
okf_github
Category
dados
Version
0.2
Last push
2026-08-26T20:42:20Z
Repository state
ativo
Language
JavaScript
Added
2026-09-08 02:26:02
Updated
2026-09-08 02:26:02
Origin id
faranahmadk/native-messaging:.knowledge/index.md

README

# Chrome Native Messaging with OpenCode

A Chrome extension that sends messages to a Python native host. The popup can also capture visible text from the current webpage and ask the installed OpenCode CLI to summarize it.

## Architecture

```text
Chrome popup (hello.html + popup.js)
        |
        | chrome.runtime.sendMessage
        v
Service worker (background.js)
        |
        | Native Messaging over stdin/stdout
        v
Python host (app/main.py)
        |
        | opencode run, prompt through stdin
        v
OpenCode CLI
```

The background service worker owns the native connection. The popup does not call `connectNative()` directly.

## Requirements

- Windows
- Google Chrome or Chromium-based browser
- Python available through the `py` launcher
- OpenCode CLI installed and authenticated
- An extension ID matching the `allowed_origins` entry in `app/native.json`

Verify Python and OpenCode:

```powershell
py --version
opencode run "Summarize this: Python is a programming language."
```

## Install OpenCode

Install OpenCode using one of the methods supported by its documentation. For an npm installation:

```powershell
npm install -g opencode
```

Confirm it is available:

```powershell
opencode --version
```

Authenticate and configure a provider/model according to your OpenCode setup. Test it directly before using the extension:

```powershell
opencode run "Summarize this: Python is a programming language."
```

## Install the Python Host

The native host uses only Python standard-library modules. No Python package installation is required.

Run a syntax check:

```powershell
py -m py_compile .\app\main.py
```

`app/main.bat` starts the host with:

```bat
call py E:\chrome-native-msg\app\main.py
```

Update that path if the project is moved.

## Register the Native Host

Chrome must know where `com.demo.hello` is registered. The manifest is located at `app/native.json`.

The current manifest points to:

```text
E:\chrome-native-msg\app\main.bat
```

Register it for the current Windows user with this PowerShell command:

```powershell
$manifest = (Resolve-Path .\app\native.json).Path
New-Item -Path 'HKCU:\Software\Google\Chrome\NativeMessagingHosts\com.demo.hello' -Force | Out-Null
New-ItemProperty -Path 'HKCU:\Software\Google\Chrome\NativeMessagingHosts\com.demo.hello' -Name '(Default)' -Value $manifest -PropertyType String -Force | Out-Null
```

For Chromium-based browsers that use a different registry location, register the same manifest under the browser's native-messaging host registry key as required by that browser.

The `allowed_origins` value in `app/native.json` must match the extension ID exactly:

```json
"allowed_origins": ["chrome-extension://YOUR_EXTENSION_ID/"]
```

Do not add a trailing path after the final slash.

## Load the Extension

1. Open `chrome://extensions`.
2. Enable **Developer mode**.
3. Click **Load unpacked**.
4. Select the `extension` folder.
5. Copy the generated extension ID.
6. Update `allowed_origins` in `app/native.json` if the ID differs.
7. Re-register the native host if the manifest path or registry entry changed.
8. Click **Reload** on the extension.

The manifest uses these permissions:

- `nativeMessaging`: communicate with the Python host.
- `activeTab`: temporarily access the active page after the user opens the extension.
- `scripting`: run the visible-text capture function in the active tab.

## Use the Extension

### Send a manual message

1. Click the extension icon.
2. Enter a message, such as `ping`, `status`, `time`, or custom text.
3. Click **Send** or press Enter.
4. The native response appears in the popup.

### Summarize the current page

1. Open a normal webpage.
2. Click the extension icon.
3. Click **Summarize current page**.
4. The extension captures `document.body.innerText`.
5. It sends this prompt to the host:

```text
summarize this: [webpage content]
```

6. The host runs:

```text
opencode run
```

The full prompt is sent through OpenCode's standard input, which avoids Windows command-line length limits.

## Test Native Messaging Directly

This sends a framed `ping` request to the Python host and prints the framed response:

```powershell
$payload = [Text.Encoding]::UTF8.GetBytes('"ping"')
$prefix = [BitConverter]::GetBytes([uint32]$payload.Length)
$input = [IO.Path]::GetTempFileName()
$output = [IO.Path]::GetTempFileName()
$errorFile = [IO.Path]::GetTempFileName()
[IO.File]::WriteAllBytes($input, $prefix + $payload)
$process = Start-Process -FilePath 'py' -ArgumentList '.\app\main.py' -RedirectStandardInput $input -RedirectStandardOutput $output -RedirectStandardError $errorFile -PassThru -WindowStyle Hidden
$process.WaitForExit(3000) | Out-Null
[IO.File]::ReadAllBytes($output)
Remove-Item $input, $output, $errorFile -Force
```

Expected response payload:

```json
"pong"
```

## Debugging

### Service worker logs

1. Open `chrome://extensions`.
2. Find the extension.
3. Click **service worker** or **Inspect views**.
4. Open the **Console** tab.

### Popup logs

Open the popup, right-click inside it, and select **Inspect**. Popup logs appear in the popup DevTools, not the service worker console.

### Native host errors

Inspect the service worker console and look for errors such as:

- `Specified native messaging host not found`
- `Access to the specified native messaging host is forbidden`
- `OpenCode CLI was not found on PATH`
- `OpenCode timed out after 120 seconds`
- `The system cannot find the path specified`

Check the native-host registration:

```powershell
Get-ItemProperty 'HKCU:\Software\Google\Chrome\NativeMessagingHosts\com.demo.hello'
```

Check the OpenCode path used by the native host:

```powershell
Get-Command opencode -All
```

`main.py` prefers `opencode.cmd`, `opencode.exe`, and `opencode`; it can also fall back to launching `opencode.ps1` through PowerShell.

## Limitations

- The extension captures visible body text only; it does not capture images, hidden content, or browser UI.
- Chrome restricted pages such as `chrome://` pages, the Chrome Web Store, PDF viewer pages, and some `file://` pages may not allow script injection.
- Prompt input is limited to 900,000 UTF-8 bytes to stay below Chrome native-messaging limits.
- Only one native request is allowed at a time. A second simultaneous request receives a busy error instead of being queued.
- OpenCode processing can take up to 120 seconds.
- The native host protocol uses a 4-byte length prefix and JSON payloads. `app/main.py` currently uses Python's native `@I` packing, matching the existing Windows-oriented protocol implementation.
- Keep stdout reserved for native-messaging protocol bytes. Host diagnostics are written to stderr.
- Webpage text may contain sensitive or untrusted content. Review the captured text before sending it to an external model provider.

## Project Files

- `extension/manifest.json`: Chrome extension configuration and permissions.
- `extension/hello.html`: popup layout and loading bar.
- `extension/popup.js`: manual messaging and active-page capture.
- `extension/background.js`: single native-port relay.
- `app/main.py`: native-message framing and OpenCode invocation.
- `app/main.bat`: starts the Python host.
- `app/native.json`: native host registration data.

## Useful Commands

```powershell
# Validate extension JavaScript
node --check .\extension\popup.js
node --check .\extension\background.js

# Validate Python
py -m py_compile .\app\main.py

# Validate OpenCode independently
opencode run "Summarize this: a short test sentence"
```

## Useful Links

- [Prompt Injection Defenses](https://www.anthropic.com/research/prompt-injection-defenses)
- [Get Started with Claude in Chrome](https://support.claude.com/en/articles/12012173-get-started-with-claude-in-chrome)
- [Chrome Extensions Permissions List](https://developer.chrome.com/docs/extensions/reference/permissions-list)
- [Build with AI](https://developer.chrome.com/docs/extensions/ai/build-with-ai)
- [Claude for Chrome](https://claude.com/blog/claude-for-chrome)

More