Google rolls out Gemini in Chrome in 7 new countries
Back to Tutorials
techTutorialintermediate

Google rolls out Gemini in Chrome in 7 new countries

April 20, 20266 views5 min read

Learn to build a Chrome extension that integrates with Google's Gemini AI API, enabling AI-powered functionality in browser environments.

Introduction

In this tutorial, you'll learn how to integrate and work with Google's Gemini API within a Chrome extension environment. This practical guide will walk you through creating a Chrome extension that leverages the Gemini AI capabilities, similar to what Google is rolling out in the mentioned countries. You'll build a functional extension that can make API calls to Gemini and display responses in a user-friendly interface.

Prerequisites

  • Basic understanding of HTML, CSS, and JavaScript
  • Chrome browser installed
  • Google Cloud account with API access enabled
  • Basic knowledge of Chrome extension development
  • Text editor (VS Code recommended)

Why this tutorial matters: Understanding how to work with AI APIs in browser extensions is crucial for developers who want to create intelligent web applications. This knowledge enables you to build powerful tools that enhance user experience by integrating cutting-edge AI capabilities directly into their browsing environment.

Step 1: Set up your Google Cloud Project

1.1 Create a new Google Cloud project

First, navigate to the Google Cloud Console and create a new project. Enable the Vertex AI API for your project.

1.2 Generate API credentials

Go to the Credentials section and create a new API key. This key will be used to authenticate your extension's requests to the Gemini API.

1.3 Configure API access

Ensure your project has the necessary permissions to access the Vertex AI API. Note down your project ID and API key for later use.

Step 2: Create the Chrome Extension Structure

2.1 Create project directory

Create a new folder called gemini-extension and inside it, create the following files:

  • manifest.json
  • popup.html
  • popup.js
  • styles.css

2.2 Set up manifest.json

This file defines your extension's properties and permissions. Create the following manifest.json:

{
  "manifest_version": 3,
  "name": "Gemini AI Assistant",
  "version": "1.0",
  "description": "Integrate Gemini AI capabilities into your browser",
  "permissions": [
    "activeTab",
    "storage"
  ],
  "action": {
    "default_popup": "popup.html",
    "default_title": "Gemini Assistant",
    "default_icon": {
      "16": "icon16.png",
      "48": "icon48.png",
      "128": "icon128.png"
    }
  },
  "background": {
    "service_worker": "background.js"
  }
}

2.3 Create the popup interface

Build the HTML structure for your extension's user interface in popup.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="container">
    <h2>Gemini AI Assistant</h2>
    <div class="input-group">
      <textarea id="userInput" placeholder="Ask something..."></textarea>
      <button id="submitBtn">Send to Gemini</button>
    </div>
    <div id="responseContainer" class="response-container"></div>
  </div>
  <script src="popup.js"></script>
</body>
</html>

Step 3: Implement the JavaScript Logic

3.1 Create the popup.js file

Implement the core functionality in popup.js:

const API_KEY = 'YOUR_API_KEY_HERE'; // Replace with your actual API key
const API_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${API_KEY}`;

const userInput = document.getElementById('userInput');
const submitBtn = document.getElementById('submitBtn');
const responseContainer = document.getElementById('responseContainer');

submitBtn.addEventListener('click', async () => {
  const query = userInput.value.trim();
  if (!query) return;

  try {
    responseContainer.innerHTML = '

Thinking...

'; const response = await fetch(API_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ contents: [{ parts: [ { text: query } ] }] }) }); const data = await response.json(); if (data.error) { responseContainer.innerHTML = `

Error: ${data.error.message}

`; return; } const geminiResponse = data.candidates[0].content.parts[0].text; responseContainer.innerHTML = `

${geminiResponse}

`; } catch (error) { responseContainer.innerHTML = `

Error: ${error.message}

`; } });

3.2 Add basic styling

Create a simple CSS file in styles.css to make your extension look professional:

.container {
  width: 400px;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.input-group {
  margin-bottom: 15px;
}

#userInput {
  width: 100%;
  height: 100px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: vertical;
}

#submitBtn {
  width: 100%;
  padding: 10px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

#submitBtn:hover {
  background-color: #3367d6;
}

.response-container {
  margin-top: 15px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-height: 50px;
}

Step 4: Load and Test Your Extension

4.1 Load the extension in Chrome

Open Chrome and navigate to chrome://extensions/. Enable Developer mode using the toggle in the top right corner. Click "Load unpacked" and select your extension directory.

4.2 Test functionality

Click on your extension icon in the toolbar, type a question in the input field, and click "Send to Gemini". You should see the AI's response displayed in the extension popup.

4.3 Debug and refine

Use the Chrome DevTools console to debug any issues. Check that your API key is correctly configured and that your extension has proper permissions.

Step 5: Enhance Extension Features

5.1 Add error handling improvements

Enhance your JavaScript to handle different error scenarios:

// Add this to your existing JavaScript
function handleError(error) {
  console.error('Gemini API Error:', error);
  responseContainer.innerHTML = '

Sorry, I encountered an error processing your request.

'; // Handle specific error types if (error.status === 400) { responseContainer.innerHTML = '

Invalid request. Please check your input.

'; } else if (error.status === 403) { responseContainer.innerHTML = '

Access denied. Please check your API key.

'; } else if (error.status === 429) { responseContainer.innerHTML = '

Rate limit exceeded. Please try again later.

'; } }

5.2 Implement request throttling

For production use, implement request throttling to prevent API abuse:

let lastRequestTime = 0;
const REQUEST_DELAY = 1000; // 1 second minimum between requests

submitBtn.addEventListener('click', async () => {
  const now = Date.now();
  if (now - lastRequestTime < REQUEST_DELAY) {
    responseContainer.innerHTML = '

Please wait before sending another request.

'; return; } lastRequestTime = now; // ... rest of your API call logic });

Summary

In this tutorial, you've built a functional Chrome extension that integrates with Google's Gemini API. You learned how to:

  • Set up a Google Cloud project with proper API access
  • Create the basic structure of a Chrome extension
  • Implement API calls to Gemini using JavaScript
  • Handle responses and errors appropriately
  • Design a user-friendly interface for AI interactions

This foundation enables you to build more sophisticated AI-powered tools that can be deployed across the countries mentioned in the Google announcement. The extension demonstrates how AI capabilities can be seamlessly integrated into browser environments, providing users with powerful tools right at their fingertips.

Remember to keep your API keys secure and consider implementing additional features like request caching, conversation history, and user preference management for a production-ready extension.

Related Articles