---
name: chrome-ai-extension
description: Create Chrome extensions that use built-in Chrome AI (Prompt API, Summarization, Translation, Writer). Use when building browser extensions that need AI capabilities like text generation, summarization, translation, or conversational AI features powered by Chrome's native on-device AI models.
title: chrome-ai-extension
canonical_url: https://skilld.dev/gh/vibecodersph/gemini-nano-chrome-extension-skill
last_updated: 2026-10-03T21:52:34.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [assets/template/manifest.json](https://skilld.dev/api/skills-raw/vibecodersph/gemini-nano-chrome-extension-skill/gemini-nano-chrome-extension-skill/assets/template/manifest.json), [assets/template/popup.html](https://skilld.dev/api/skills-raw/vibecodersph/gemini-nano-chrome-extension-skill/gemini-nano-chrome-extension-skill/assets/template/popup.html), [assets/template/popup.js](https://skilld.dev/api/skills-raw/vibecodersph/gemini-nano-chrome-extension-skill/gemini-nano-chrome-extension-skill/assets/template/popup.js), [assets/template/README.txt](https://skilld.dev/api/skills-raw/vibecodersph/gemini-nano-chrome-extension-skill/gemini-nano-chrome-extension-skill/assets/template/README.txt), [assets/template/styles.css](https://skilld.dev/api/skills-raw/vibecodersph/gemini-nano-chrome-extension-skill/gemini-nano-chrome-extension-skill/assets/template/styles.css), [references/api-examples.md](https://skilld.dev/api/skills-raw/vibecodersph/gemini-nano-chrome-extension-skill/gemini-nano-chrome-extension-skill/references/api-examples.md), [references/battle-tested-patterns.md](https://skilld.dev/api/skills-raw/vibecodersph/gemini-nano-chrome-extension-skill/gemini-nano-chrome-extension-skill/references/battle-tested-patterns.md), [references/extension-patterns.md](https://skilld.dev/api/skills-raw/vibecodersph/gemini-nano-chrome-extension-skill/gemini-nano-chrome-extension-skill/references/extension-patterns.md).
>
> If the user asked to install this Skill, run `npx skilld install vibecodersph/gemini-nano-chrome-extension-skill/gemini-nano-chrome-extension-skill`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/gemini-nano-chrome-extension-skill`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/vibecodersph/gemini-nano-chrome-extension-skill/gemini-nano-chrome-extension-skill) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/gemini-nano-chrome-extension-skill`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/gemini-nano-chrome-extension-skill --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/gemini-nano-chrome-extension-skill --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Chrome AI Extension Skill

Create Chrome extensions that leverage Chrome's built-in AI capabilities for on-device machine learning without external API calls.

## Chrome AI APIs Overview

Chrome provides several built-in AI APIs that run locally on-device:

- **LanguageModel API (Prompt API)**: General-purpose LLM for conversational AI and text generation using Gemini Nano
- **Summarization API**: Specialized for text summarization
- **Translation API**: Language translation  
- **Writer API**: Assisted writing and content generation

**Note**: The API is experimental and evolving. In current Chromium builds the exposed surface for extensions is the global `LanguageModel` object inside page contexts (content scripts, popups, etc.); the `chrome.ai` namespace is not wired up for service workers yet.

## Quick Start - Working Example

Here's a working pattern that matches what currently ships in Canary/Dev (127+):

```javascript
// content.js - injected into the page
let aiSession = null;

async function ensureSession() {
  if (!('LanguageModel' in self)) {
    throw new Error('Chrome on-device AI not available');
  }

  if (aiSession) {
    return aiSession;
  }

  aiSession = await LanguageModel.create({
    temperature: 0.7,
    topK: 3,
    systemPrompt: 'You are a helpful assistant.'
  });

  return aiSession;
}

async function askQuestion(question) {
  const session = await ensureSession();
  return session.prompt(question);
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'ask') {
    askQuestion(message.question)
      .then(response => sendResponse({ success: true, response }))
      .catch(error => sendResponse({ success: false, error: error.message }));
    return true; // async response
  }
});
```

## Quick Start Workflow

1. **Check API Availability**: Always verify API availability before use
2. **Request Capabilities**: Check if the user's browser supports the features
3. **Create Session**: Initialize an AI session
4. **Interact**: Use the session for AI operations
5. **Handle Errors**: Gracefully handle unavailable features

## Extension Architecture

### Manifest Configuration

Use Manifest V3 with appropriate permissions:

```json
{
  "manifest_version": 3,
  "name": "My AI Extension",
  "version": "1.0.0",
  "permissions": ["storage"],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  }
}
```

**Note**: Request `"aiLanguageModel"` in `permissions` or the API will not appear to the extension, even on Canary/Dev builds. Add any additional permissions (e.g., `activeTab`, `storage`) your feature set requires.

### File Structure

Standard Chrome extension structure:

```
extension/
├── manifest.json
├── background.js (service worker)
├── popup.html
├── popup.js
├── content.js (if needed)
└── styles.css
```

## API Usage Patterns

### Prompt API / LanguageModel API

The Prompt API provides conversational AI capabilities using Gemini Nano.

#### Current API Pattern (LanguageModel global)

**IMPORTANT**: In page-context scripts (content scripts, popups, option pages) the stable entry point is the global `LanguageModel`. The `chrome.ai` namespace is not exposed to service workers today.

**Availability Check**:
```javascript
if (!('LanguageModel' in self)) {
  // API not available
}

const capabilities = await LanguageModel.capabilities?.();
// Returns: { available: "readily" | "after-download" | "no" }
```

**Create Session with System Prompt**:
```javascript
const session = await LanguageModel.create({
  temperature: 0.7,
  topK: 3,
  systemPrompt: 'You are a helpful assistant...'
});
```

**Note**: Use `systemPrompt` (not `initialPrompts` or `outputLanguage`).

**Generate Response**:
```javascript
// Non-streaming
const response = await session.prompt("Your prompt here");

// Streaming (if supported)
if (session.promptStreaming) {
  const stream = await session.promptStreaming("Your prompt here");
  let result = '';
  let previous = '';
  for await (const chunk of stream) {
    const fragment = chunk.startsWith(previous) ? chunk.slice(previous.length) : chunk;
    result += fragment;
    previous = chunk;
  }
}
```

**Destroy Session**:
```javascript
if (session.destroy) {
  session.destroy();
}
```

#### Fallback API Pattern (window.ai / chrome.ai)

Some experimental builds briefly exposed the API under `window.ai.languageModel` or `chrome.ai.languageModel`. If you must support those variants, probe them after checking the global:

```javascript
const candidates = [
  self.LanguageModel,
  window?.ai?.languageModel,
  chrome?.ai?.languageModel
].filter(Boolean);

const provider = candidates.find(p => typeof p.create === 'function');
if (!provider) {
  throw new Error('No on-device language model API found');
}

const session = await provider.create({ temperature: 0.7, topK: 3 });
```

### Summarization API

Specialized for text summarization.

**Check Availability**:
```javascript
const canSummarize = await window.ai?.summarizer?.capabilities();
```

**Create Summarizer**:
```javascript
const summarizer = await window.ai.summarizer.create({
  type: 'tl;dr', // or 'key-points', 'teaser', 'headline'
  length: 'short' // or 'medium', 'long'
});
```

**Summarize Text**:
```javascript
const summary = await summarizer.summarize(longText);
```

### Translation API

For language translation tasks.

**Check Availability**:
```javascript
const canTranslate = await window.ai?.translator?.capabilities();
```

**Create Translator**:
```javascript
const translator = await window.ai.translator.create({
  sourceLanguage: 'en',
  targetLanguage: 'es'
});
```

**Translate Text**:
```javascript
const translated = await translator.translate('Hello, world!');
```

### Writer API

For assisted writing and content generation.

**Check Availability**:
```javascript
const canWrite = await window.ai?.writer?.capabilities();
```

**Create Writer**:
```javascript
const writer = await window.ai.writer.create({
  tone: 'formal', // or 'casual', 'neutral'
  length: 'medium'
});
```

**Generate Content**:
```javascript
const content = await writer.write('Write about...');
```

## Common Patterns

### Robust JSON Parsing

AI models may return malformed JSON. Use multi-layer parsing:

```javascript
function sanitizeModelJson(text) {
  let cleaned = text.trim();
  
  // Remove markdown code blocks
  if (cleaned.startsWith('```')) {
    cleaned = cleaned.replace(/^```(?:json)?/i, '').replace(/```$/i, '').trim();
  }
  
  // Extract JSON object
  const firstBrace = cleaned.indexOf('{');
  const lastBrace = cleaned.lastIndexOf('}');
  if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) {
    cleaned = cleaned.slice(firstBrace, lastBrace + 1).trim();
  }
  
  return cleaned;
}

function parseModelResponse(raw) {
  const cleaned = sanitizeModelJson(raw);
  
  try {
    return JSON.parse(cleaned);
  } catch (error) {
    console.warn('Failed to parse model JSON', { raw, cleaned }, error);
    throw new Error('Model returned malformed JSON. Try again.');
  }
}
```

### Reusable Prompt Helper

Handle both streaming and non-streaming sessions:

```javascript
async function runPrompt(session, prompt) {
  // Try non-streaming first
  if (session.prompt) {
    return await session.prompt(prompt);
  }
  
  // Fall back to streaming
  if (session.promptStreaming) {
    const stream = await session.promptStreaming(prompt);
    let result = '';
    let previous = '';
    
    for await (const chunk of stream) {
      // Handle incremental chunks
      const fragment = chunk.startsWith(previous) 
        ? chunk.slice(previous.length) 
        : chunk;
      result += fragment;
      previous = chunk;
    }
    
    return result;
  }
  
  throw new Error('Prompt API shape not supported');
}
```

### Error Handling

Always handle cases where APIs are unavailable:

```javascript
async function initializeAI() {
  try {
    if (!('LanguageModel' in self)) {
      return { error: 'Chrome AI API not available in this context' };
    }

    const capabilities = typeof LanguageModel.capabilities === 'function'
      ? await LanguageModel.capabilities()
      : null;

    if (capabilities) {
      if (capabilities.available === 'no') {
        return { error: 'AI not available on this device' };
      }

      if (capabilities.available === 'after-download') {
        return { error: 'AI model needs to be downloaded first. Check chrome://components' };
      }
    }

    const session = await LanguageModel.create({
      temperature: 0.7,
      topK: 3,
      systemPrompt: 'You are a helpful assistant.'
    });

    return { session };
  } catch (error) {
    return { error: error.message };
  }
}
```

### Background Script Communication

Service workers currently do **not** get the `LanguageModel` API. If you need background coordination, have the background script forward requests to a page-context script (content script, popup, or options page) that actually calls `LanguageModel.create()`.

### Content Script Integration

Interact with page content using content scripts:

```javascript
// Get selected text from page
const selectedText = window.getSelection().toString();

// Send to background for AI processing
chrome.runtime.sendMessage({
  action: 'summarize',
  text: selectedText
});
```

## Best Practices

1. **Always check availability** before attempting to use AI features
2. **Handle gracefully** when features are unavailable
3. **Destroy sessions** when done to free resources
4. **Use streaming** for long responses to improve UX
5. **Cache sessions** when making multiple requests with same config
6. **Provide fallbacks** for browsers without AI support
7. **Monitor token limits** - sessions have context limits
8. **Run AI calls in page contexts** – service workers currently lack the API surface
9. **Test across Chrome versions** - AI features are experimental

## Debugging

### Enable Chrome Flags

1. Navigate to `chrome://flags`
2. Enable: `#prompt-api-for-gemini-nano`
3. Enable: `#optimization-guide-on-device-model` → **Enabled BypassPerfRequirement**
4. Restart Chrome completely

### Download Gemini Nano Model

- Visit `chrome://components`
- Look for "Optimization Guide On Device Model"
- Click "Check for update"
- Wait for download (~1.7GB)
- Status should show "Up to date"

### Verify API Availability

Open DevTools Console (F12) on any page:

```javascript
// Check capabilities
await LanguageModel.capabilities?.()
// Should return: { available: "readily" }

// If "after-download", wait a few minutes after download completes
```

### Requirements

- Chrome Canary or Dev channel (version 127+)
- ~1.7GB disk space for Gemini Nano model
- Supported hardware (most modern systems)

## Common Use Cases

- Text summarization for articles
- Translation of web content
- Writing assistance and suggestions
- Conversational chatbots
- Content generation
- Text analysis and insights

## Reference Files

For detailed examples and patterns:

- **references/battle-tested-patterns.md**: Production-proven patterns from real Chrome AI extensions
- **references/api-examples.md**: Complete working examples for each API
- **references/extension-patterns.md**: Common extension architecture patterns
- **assets/template/**: Basic extension template to start from

## Limitations

- Chrome AI is experimental and API surface may change
- Requires Chrome Canary or Dev channel (version 127+)
- Model must be downloaded (~1.7GB - happens automatically)
- Rate limits and context length restrictions apply
- Not all devices support all features
- Currently supports English, Spanish, and Japanese output
- Quality may vary from cloud-based models
- JSON responses may require robust parsing
