0Pricing
Browser Extensions Development (Chrome & Edge) · Lekcja

Komunikacja między komponentami interfejsu

Utwórz kanały komunikacji dla popupów, stron opcji i skryptów działających w tle, aby zapewnić płynny przepływ danych.

Komunikacja między komponentami interfejsu to bezpłatna lekcja Browser Extensions Development (Chrome & Edge) na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Browser Extensions Development (Chrome & Edge), a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Browser Extensions Development (Chrome & Edge) zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Bridge Your Extension Components

Browser extensions are made of several parts: popups, options pages, and background scripts. Each part often runs in its own isolated environment.

To build powerful extensions, these components need to talk to each other. This lesson shows you how to establish messaging channels for seamless data flow.

Isolated Environments

Think of your extension's popup, options page, and background script as separate mini-programs. They don't automatically share data or functions.

  • Popup: Appears when clicked, then closes.
  • Options Page: A dedicated settings page.
  • Background Script: Runs continuously, handles events.

Messaging allows them to send information and trigger actions across these boundaries.

UI Components Send Messages

To send a message from your popup or options page to the background script, you use the chrome.runtime.sendMessage() API.

This function lets you pass a JSON object (your message) to other parts of your extension. It's great for triggering actions or sending user input.

Popup to Background Example

Here's how a popup script might send a message to the background script, for instance, to toggle a feature. This JavaScript would be in your popup.js file, linked from popup.html.

// popup.js
document.getElementById('toggleButton').addEventListener('click', () => {
  chrome.runtime.sendMessage({ action: 'toggleFeature', value: true }, (response) => {
    console.log('Received response:', response);
  });
});

Background Listens for Messages

Your background script needs to listen for incoming messages. It does this using the chrome.runtime.onMessage.addListener() event.

This listener will fire whenever any part of your extension (like a popup or options page) sends a message via chrome.runtime.sendMessage().

Background Script Listener

This snippet shows a basic message listener in your background service worker (e.g., background.js). It checks the message's action and performs a task.

// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'toggleFeature') {
    console.log('Feature toggled:', message.value);
    // Perform background task here
    sendResponse({ status: 'success', message: 'Feature updated!' });
  }
  // Important: Return true to indicate you want to send a response asynchronously
  return true; 
});

Sending a Response Back

Often, the component that sent the message (e.g., your popup) needs to know if the action was successful or receive data back.

The sendResponse function, provided as the third argument to your onMessage listener, allows the background script to send a one-time reply to the original sender.

Handling Background Responses

The callback function in chrome.runtime.sendMessage() is where your popup or options page receives the response from the background script. This completes the two-way communication.

// popup.js (modified)
document.getElementById('toggleButton').addEventListener('click', () => {
  chrome.runtime.sendMessage({ action: 'toggleFeature', value: true }, (response) => {
    if (chrome.runtime.lastError) {
      console.error('Error sending message:', chrome.runtime.lastError.message);
      return;
    }
    console.log('Background response:', response);
    // Update popup UI based on response
    document.getElementById('status').textContent = response.message;
  });
});

Options Pages Communicate Too

The same chrome.runtime.sendMessage() and chrome.runtime.onMessage.addListener() pattern applies to communication involving your options page.

An options page can send user-defined settings to the background script for persistence, and the background can reply with confirmation or fetched data.

Messaging Concepts

Consider an extension where a popup needs to ask the background script for the current count of unread notifications.

Which API should the popup use to initiate this request?

Recap: Seamless Data Flow

You've learned how to enable communication between your extension's UI components (popups, options pages) and its background script!

  • Use chrome.runtime.sendMessage() to send data.
  • Use chrome.runtime.onMessage.addListener() to receive data and respond.

This fundamental skill allows your extension's different parts to work together effectively.

Często zadawane pytania

Czy lekcja „Komunikacja między komponentami interfejsu” jest bezpłatna?

Tak — pełny tekst „Komunikacja między komponentami interfejsu” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Browser Extensions Development (Chrome & Edge), przejdź na CoddyKit PRO. Kurs Browser Extensions Development (Chrome & Edge) zawiera 4 lekcji w sumie.

Co nauczysz się w „Komunikacja między komponentami interfejsu”?

Utwórz kanały komunikacji dla popupów, stron opcji i skryptów działających w tle, aby zapewnić płynny przepływ danych. Ćwiczysz Browser Extensions Development (Chrome & Edge) z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Browser Extensions Development (Chrome & Edge)?

Nie wymagamy żadnego doświadczenia. Browser Extensions Development (Chrome & Edge) w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Komunikacja między komponentami interfejsu”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Browser Extensions Development (Chrome & Edge)?

Tak. Każda lekcja Browser Extensions Development (Chrome & Edge) zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Tworzenie interaktywnego interfejsu popup
  2. Tworzenie strony opcji
  3. Komunikacja między komponentami interfejsu
  4. Motywy CSS i obsługa trybu ciemnego
← Powrót do Browser Extensions Development (Chrome & Edge)