Chrome Extension Automation Guide
Creating a Chrome Extension for Automation in Python
1. Understand the Structure:
- A Chrome extension consists of HTML, CSS, and JavaScript files.
- Background script communicates with your Python script.
- Use
chrome.runtime.sendMessage
API for communication.
2. Create the Chrome Extension:
{
"manifest_version": 2,
"name": "My Extension",
"version": "1.0",
"permissions": [
"activeTab",
"storage"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/icon16.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
}
},
"icons": {
"16": "images/icon16.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
}
}
3. Create Background Script:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.message === "startAutomation") {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {message: "startAutomation"});
});
}
}
);
4. Inject Automation Script:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.message === "startAutomation") {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.executeScript(tabs[0].id, {file: "automation.js"});
});
}
}
);
5. Create Automation Script:
// Sample automation script using Selenium
console.log("Automation script started");
// Your Selenium automation code goes here
6. Python Script:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
options = Options()
options.add_extension("path/to/your/extension_directory")
driver = webdriver.Chrome(chrome_options=options)
# Open a URL or perform any other automation tasks
# Trigger the extension to start automation
driver.execute_script('chrome.runtime.sendMessage({message: "startAutomation"});')
time.sleep(5) # Give some time for the automation to run
driver.quit()