Respuesta a la entrada del omnibox
Procese la entrada de los usuarios desde el omnibox, proporcione sugerencias y ejecute lógica personalizada según el texto introducido.
Respuesta a la entrada del omnibox es una lección gratuita de Browser Extensions Development (Chrome & Edge) en CoddyKit. Esta es la lección 3 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.
Responding to Omnibox Input
Welcome to the lesson on making your extension smart! We've learned how to set up an omnibox keyword. Now, let's make it respond to user input.
The omnibox (address bar) is a powerful place. Your extension can listen for what users type after your keyword and react in two main ways:
- Provide suggestions: Guide the user as they type.
- Execute actions: Perform tasks when they press Enter.
The Omnibox API
To interact with the omnibox, we use the chrome.omnibox API. This API lives in your extension's background script (service worker).
Remember to declare the "omnibox" permission in your manifest.json file for your extension to use this API.
Listening for Input Changes
As a user types after your omnibox keyword, your extension can provide dynamic suggestions. This is handled by the chrome.omnibox.onInputChanged event.
- It fires every time the user's input changes.
- You receive the current
textthe user has typed. - You get a
suggestcallback function to send suggestions back to the omnibox.
Structuring Your Suggestions
The suggest callback expects an array of suggestion objects. Each object needs an "content" field, which is the actual text that will be inserted if the user selects the suggestion.
You can also add a "description" field for richer suggestions:
content: The text to use if the suggestion is selected.description: (Optional) Rich HTML text displayed next to the suggestion.
Code: Dynamic Suggestions
Let's create a background script that suggests a prefix based on the user's input. Make sure your manifest.json has "omnibox": { "keyword": "go" } and the "omnibox" permission.
chrome.omnibox.onInputChanged.addListener(
(text, suggest) => {
const suggestions = [
{ content: text + " search", description: "Search for: " + text },
{ content: text + " docs", description: "Docs for: " + text }
];
suggest(suggestions);
}
);Executing Actions on Enter
Once the user types their input and presses the Enter key, the chrome.omnibox.onInputEntered event is triggered. This is where you perform the main action of your extension.
- It provides the final
textentered by the user. - It also gives a
disposition, indicating how the user wants the action to be handled (e.g., new tab, current tab).
Code: Opening a New Tab
Here's how to open a new tab with a search query based on the user's input. This code would typically be in the same background script as onInputChanged.
chrome.omnibox.onInputEntered.addListener(
(text, disposition) => {
const searchUrl = `https://www.google.com/search?q=${encodeURIComponent(text)}`;
if (disposition === 'newForegroundTab') {
chrome.tabs.create({ url: searchUrl });
} else if (disposition === 'newBackgroundTab') {
chrome.tabs.create({ url: searchUrl, active: false });
} else {
// currentTab
chrome.tabs.update({ url: searchUrl });
}
}
);Setting a Default Suggestion
You can provide a default suggestion that appears even before the user types anything. This is useful for guiding users or showing a common action.
Use chrome.omnibox.setDefaultSuggestion() with a description to set this initial hint.
chrome.omnibox.setDefaultSuggestion({
description: 'Type a query to search Google'
});Rich Suggestions with Descriptions
For even more helpful suggestions, you can use HTML within the description field. This allows you to highlight parts of the text, use different colors, or make it more readable.
- Use
<match>tags to highlight matching text. - Use
<dim>tags for less important text. - Remember to escape special characters like
<and>if they are part of your literal text.
Quick Check: Omnibox Events
Consider an extension that uses the omnibox keyword 'wiki'. Which event listener is primarily responsible for updating suggestions as the user types 'wiki cats'?
Recap: Responding to Omnibox Input
You've learned how to make your extension truly interactive with the omnibox!
- We use
chrome.omnibox.onInputChangedto provide dynamic suggestions as the user types. - Suggestions are an array of objects with
contentand optionaldescriptionfields. chrome.omnibox.onInputEnteredallows your extension to execute a specific action when the user presses Enter.- You can also set a
setDefaultSuggestionfor initial guidance.
This powerful API lets users interact with your extension directly from the browser's address bar, making common tasks quicker and more efficient.
Preguntas frecuentes
¿La lección «Respuesta a la entrada del omnibox» es gratis?
Sí — el texto completo de «Respuesta a la entrada del omnibox» 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 «Respuesta a la entrada del omnibox»?
Procese la entrada de los usuarios desde el omnibox, proporcione sugerencias y ejecute lógica personalizada según el texto introducido. 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 3 de 4.
¿Cuánto tiempo toma la lección «Respuesta a la entrada del omnibox»?
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
- Adición de elementos al menú contextual
- Integración de palabras clave del omnibox
- Respuesta a la entrada del omnibox
- Atajos de teclado con la API Commands