AI Browser Agent Chrome Extension
Below is a complete implementation for a Chrome extension that allows an AI agent to control your browser. This includes both the extension files and a basic AI agent that can interpret commands.
File Structure
browser-ai-agent/
├── manifest.json
├── background.js
├── content.js
├── popup/
│ ├── popup.html
│ ├── popup.js
│ └── popup.css
└── icons/
├── icon16.png
├── icon48.png
└── icon128.png
1. manifest.json
{
"manifest_version": 3,
"name": "AI Browser Agent",
"version": "1.0",
"description": "An AI agent that controls your browser",
"permissions": [
"activeTab",
"scripting",
"tabs",
"storage",
"webNavigation",
"commands"
],
"host_permissions": [
"<all_urls>"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup/popup.html",
"default_icon": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"commands": {
"toggle_agent": {
"suggested_key": {
"default": "Ctrl+Shift+A",
"mac": "Command+Shift+A"
},
"description": "Toggle AI Agent"
}
},
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
}
2. background.js
// Background script for the AI agent
let isAgentActive = false;
let currentTabId = null;
// Listen for commands
chrome.commands.onCommand.addListener((command) => {
if (command === "toggle_agent") {
toggleAgent();
}
});
// Toggle the AI agent on/off
function toggleAgent() {
isAgentActive = !isAgentActive;
chrome.storage.local.set({ isAgentActive });
if (isAgentActive) {
chrome.action.setBadgeText({ text: "ON" });
chrome.action.setBadgeBackgroundColor({ color: "#4CAF50" });
startListening();
} else {
chrome.action.setBadgeText({ text: "" });
stopListening();
}
}
// Start listening for user input
function startListening() {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
currentTabId = tabs[0].id;
chrome.scripting.executeScript({
target: { tabId: currentTabId },
func: injectContentScript
});
});
}
// Stop listening for user input
function stopListening() {
if (currentTabId) {
chrome.scripting.executeScript({
target: { tabId: currentTabId },
func: removeContentScript
});
}
}
// Handle messages from content script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === "USER_COMMAND") {
processCommand(request.command);
}
});
// Process the user command with AI
async function processCommand(command) {
try {
// In a real implementation, this would call your AI service
const aiResponse = await getAIResponse(command);
// Execute the AI's response
executeAIAction(aiResponse);
// Send response back to content script
chrome.tabs.sendMessage(currentTabId, {
type: "AI_RESPONSE",
response: aiResponse
});
} catch (error) {
console.error("Error processing command:", error);
}
}
// Simulate AI response (replace with actual AI API call)
async function getAIResponse(command) {
// This is a mock implementation - replace with real AI API call
return new Promise((resolve) => {
setTimeout(() => {
// Simple command parsing - in reality, your AI would handle this
const lowerCommand = command.toLowerCase();
if (lowerCommand.includes("open") || lowerCommand.includes("go to")) {
const urlMatch = lowerCommand.match(/https?:\/\/[^\s]+/);
if (urlMatch) {
resolve({
action: "navigate",
url: urlMatch[0]
});
} else {
// Try to extract domain
const domainMatch = lowerCommand.match(/open\s+([^\s]+)/i);
if (domainMatch) {
resolve({
action: "navigate",
url: `https://www.${domainMatch[1].replace(/[^a-zA-Z0-9.]/g, '')}`
});
}
}
} else if (lowerCommand.includes("click")) {
resolve({
action: "click",
selector: extractSelectorFromCommand(command)
});
} else if (lowerCommand.includes("type")) {
const textMatch = lowerCommand.match(/type\s+"([^"]+)"/i);
if (textMatch) {
resolve({
action: "type",
text: textMatch[1],
selector: extractSelectorFromCommand(command)
});
}
} else if (lowerCommand.includes("scroll")) {
resolve({
action: "scroll",
direction: lowerCommand.includes("down") ? "down" : "up"
});
} else {
resolve({
action: "unknown",
response: "I'm not sure how to handle that command. Try something like 'Open google.com' or 'Click the search button'."
});
}
}, 500);
});
}
// Helper function to extract selector from command
function extractSelectorFromCommand(command) {
const lowerCommand = command.toLowerCase();
if (lowerCommand.includes("button")) return "button";
if (lowerCommand.includes("link")) return "a";
if (lowerCommand.includes("search")) return "input[type='text'], input[type='search']";
if (lowerCommand.includes("submit")) return "input[type='submit'], button[type='submit']";
return "body";
}
// Execute the AI's action
function executeAIAction(action) {
if (!currentTabId) return;
switch (action.action) {
case "navigate":
chrome.tabs.update(currentTabId, { url: action.url });
break;
case "click":
chrome.scripting.executeScript({
target: { tabId: currentTabId },
func: clickElement,
args: [action.selector]
});
break;
case "type":
chrome.scripting.executeScript({
target: { tabId: currentTabId },
func: typeInElement,
args: [action.selector, action.text]
});
break;
case "scroll":
chrome.scripting.executeScript({
target: { tabId: currentTabId },
func: scrollPage,
args: [action.direction]
});
break;
}
}
// Functions to be injected into the page
function injectContentScript() {
window.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.shiftKey && e.key === 'A') {
const command = prompt("What would you like the AI to do?");
if (command) {
chrome.runtime.sendMessage({
type: "USER_COMMAND",
command: command
});
}
}
});
}
function removeContentScript() {
window.removeEventListener('keydown', () => {});
}
function clickElement(selector) {
const element = document.querySelector(selector);
if (element) {
element.click();
}
}
function typeInElement(selector, text) {
const element = document.querySelector(selector);
if (element) {
element.focus();
element.value = text;
element.dispatchEvent(new Event('input', { bubbles: true }));
element.dispatchEvent(new Event('change', { bubbles: true }));
}
}
function scrollPage(direction) {
window.scrollBy({
top: direction === 'down' ? window.innerHeight : -window.innerHeight,
behavior: 'smooth'
});
}
3. content.js
// Content script for the AI agent
console.log("AI Browser Agent content script loaded");
// Listen for messages from the background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === "AI_RESPONSE") {
// Display the AI's response to the user
const responseElement = document.createElement('div');
responseElement.style.position = 'fixed';
responseElement.style.bottom = '20px';
responseElement.style.right = '20px';
responseElement.style.padding = '10px';
responseElement.style.backgroundColor = '#333';
responseElement.style.color = '#fff';
responseElement.style.borderRadius = '5px';
responseElement.style.zIndex = '9999';
responseElement.style.maxWidth = '300px';
responseElement.textContent = `AI: ${request.response.response || request.response.action}`;
document.body.appendChild(responseElement);
// Remove the message after 5 seconds
setTimeout(() => {
responseElement.remove();
}, 5000);
}
});
4. popup/popup.html
<!DOCTYPE html>
<html>
<head>
<title>AI Browser Agent</title>
<link rel="stylesheet" href="popup.css">
</head>
<body>
<div class="container">
<h1>AI Browser Agent</h1>
<div class="status" id="status">Status: Off</div>
<button id="toggleButton">Activate Agent</button>
<div class="command-input">
<input type="text" id="commandInput" placeholder="Enter command...">
<button id="sendCommand">Send</button>
</div>
<div class="response" id="response"></div>
</div>
<script src="popup.js"></script>
</body>
</html>
5. popup/popup.css
body {
width: 300px;
padding: 10px;
font-family: Arial, sans-serif;
}
.container {
display: flex;
flex-direction: column;
gap: 10px;
}
h1 {
font-size: 18px;
margin: 0 0 10px 0;
color: #333;
}
.status {
padding: 5px;
text-align: center;
background-color: #f0f0f0;
border-radius: 3px;
}
button {
padding: 8px 12px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.command-input {
display: flex;
gap: 5px;
}
input {
flex: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 3px;
}
.response {
margin-top: 10px;
padding: 8px;
background-color: #f8f8f8;
border-radius: 3px;
min-height: 20px;
}
6. popup/popup.js
document.addEventListener('DOMContentLoaded', () => {
const toggleButton = document.getElementById('toggleButton');
const statusElement = document.getElementById('status');
const commandInput = document.getElementById('commandInput');
const sendCommand = document.getElementById('sendCommand');
const responseElement = document.getElementById('response');
// Check current status
chrome.storage.local.get(['isAgentActive'], (result) => {
isAgentActive = result.isAgentActive || false;
updateUI();
});
// Toggle button click handler
toggleButton.addEventListener('click', () => {
chrome.runtime.sendMessage({ action: "toggleAgent" }, (response) => {
isAgentActive = !isAgentActive;
updateUI();
});
});
// Send command button click handler
sendCommand.addEventListener('click', () => {
const command = commandInput.value.trim();
if (command) {
chrome.runtime.sendMessage({
type: "USER_COMMAND",
command: command
}, (response) => {
responseElement.textContent = response || "Command sent to AI agent";
commandInput.value = '';
});
}
});
// Update UI based on agent status
function updateUI() {
if (isAgentActive) {
statusElement.textContent = "Status: Active";
statusElement.style.backgroundColor = "#4CAF50";
toggleButton.textContent = "Deactivate Agent";
} else {
statusElement.textContent = "Status: Off";
statusElement.style.backgroundColor = "#f0f0f0";
toggleButton.textContent = "Activate Agent";
}
}
});
How to Use This Extension
- Create a folder with the structure shown above
- Add all the files with the provided content
- Add some simple icon images (16x16, 48x48, 128x128 pixels)
- In Chrome, go to
chrome://extensions/
- Enable "Developer mode" (toggle in top right)
- Click "Load unpacked" and select your folder
- The extension will now be installed
Features
- Toggle Activation: Press Ctrl+Shift+A (Cmd+Shift+A on Mac) to toggle the agent
- Command Input: Type commands in the popup or use the keyboard shortcut
- Basic Actions: The agent can:
- Navigate to URLs
- Click elements
- Type text
- Scroll pages
- Visual Feedback: Shows responses from the AI agent
Next Steps for Improvement
- Connect to Real AI: Replace the mock AI response with calls to a real AI API
- More Commands: Add support for more complex browser interactions
- Natural Language Processing: Improve command understanding
- Context Awareness: Make the agent aware of the current page context
- Security: Add proper permission checks and user confirmation for sensitive actions
This implementation provides a foundation that you can build upon to create a more sophisticated AI browser agent.