Inyección de scripts de contenido
Aprenda a inyectar JavaScript y CSS en páginas web específicas para que su extensión pueda modificar su apariencia y comportamiento.
Inyección de scripts de contenido es una lección gratuita de Browser Extensions Development (Chrome & Edge) en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Browser Extensions Development (Chrome & Edge), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Browser Extensions Development (Chrome & Edge) incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
What are Content Scripts?
Welcome to Content Scripts! These are JavaScript files that run in the context of web pages loaded in the browser.
Think of them as a bridge. They allow your extension to interact with the web page's content, just like a script running directly on that page.
- Read details from a page.
- Modify the page's appearance.
- Add or remove elements.
The Isolated World
Content scripts run in an 'isolated world'. This means they don't interfere with the page's own JavaScript environment.
Your script can access and modify the page's Document Object Model (DOM), but it can't directly access JavaScript variables or functions defined by the web page itself.
This isolation prevents conflicts and ensures your extension doesn't break the web page's functionality.
Static Injection via manifest.json
The simplest way to inject content scripts is by declaring them in your extension's manifest.json file.
These scripts will automatically load and run on web pages that match the patterns you specify. It's great for scripts that need to be active whenever a certain type of page loads.
Static JS Injection Example
Here's how you'd set up a content script in your manifest.json to inject a JavaScript file called content.js:
{ "manifest_version": 3,
"name": "My Page Modifier",
"version": "1.0",
"content_scripts": [
{
"matches": ["https://*.example.com/*"],
"js": ["content.js"]
}
]
}Static CSS Injection Example
You can also inject CSS files using the same content_scripts field in your manifest.json. This is perfect for custom styling!
The CSS will apply to matching pages, modifying their visual appearance.
{ "manifest_version": 3,
"name": "My Page Styler",
"version": "1.0",
"content_scripts": [
{
"matches": ["*://*.google.com/*"],
"css": ["content.css"]
}
]
}Programmatic Injection
Sometimes you need more control over when a script is injected. This is where programmatic injection comes in.
You can inject scripts dynamically based on user actions (like clicking a button in your popup) or specific conditions, rather than automatically on page load.
Using chrome.scripting.executeScript()
To inject scripts programmatically, you use the chrome.scripting.executeScript() API from your extension's background script or popup.
This method requires the scripting permission in your manifest.json.
- It targets a specific tab.
- You can inject a function or a file.
- Perfect for on-demand interactions.
Programmatic Code Demo
This example shows a background script injecting a simple function into the active tab when the extension icon is clicked.
The injected function changes the page's background color. Try running it!
// manifest.json snippet:
// {"permissions": ["activeTab", "scripting"]}
// background.js
chrome.action.onClicked.addListener(async (tab) => {
if (tab.url.startsWith("http")) {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => {
document.body.style.backgroundColor = 'lightblue';
console.log('Background changed!');
}
});
}
});Permissions & Best Practices
For programmatic injection, you'll typically need the activeTab and scripting permissions.
activeTab: Grants temporary host permissions to the currently active tab when the user invokes the extension.scripting: Allows using thechrome.scriptingAPI to inject code.
Always request the minimum necessary permissions for your extension's functionality.
Quick Check
Which of the following statements about content scripts is TRUE?
Recap: Injecting Content Scripts
You've learned how to inject content scripts into web pages!
- Content scripts let your extension interact with web pages.
- They run in an isolated world to prevent conflicts.
- You can inject them statically via
manifest.jsonfor automatic loading. - Or, inject them programmatically using
chrome.scripting.executeScript()for on-demand actions.
Next, we'll dive into how to modify the DOM of web pages using these powerful scripts!
Preguntas frecuentes
¿La lección «Inyección de scripts de contenido» es gratis?
Sí — el texto completo de «Inyección de scripts de contenido» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Browser Extensions Development (Chrome & Edge), actualiza a CoddyKit PRO. El curso de Browser Extensions Development (Chrome & Edge) incluye 4 lecciones en total.
¿Qué aprenderé en «Inyección de scripts de contenido»?
Aprenda a inyectar JavaScript y CSS en páginas web específicas para que su extensión pueda modificar su apariencia y comportamiento. Practicas Browser Extensions Development (Chrome & Edge) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Browser Extensions Development (Chrome & Edge)?
No se requiere experiencia previa. Browser Extensions Development (Chrome & Edge) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «Inyección de scripts de contenido»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Browser Extensions Development (Chrome & Edge)?
Sí. Cada lección de Browser Extensions Development (Chrome & Edge) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Inyección de scripts de contenido
- Modificación del DOM de páginas web
- Interacción con datos de páginas web
- Inyección de CSS y estilos aislados