0Pricing
Browser Extensions Development (Chrome & Edge) · Урок

Внедрение контентных скриптов

Научитесь внедрять JavaScript и CSS в определённые веб-страницы, чтобы расширение могло изменять их внешний вид и поведение.

«Внедрение контентных скриптов» — бесплатный урок Browser Extensions Development (Chrome & Edge) на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Browser Extensions Development (Chrome & Edge), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Browser Extensions Development (Chrome & Edge) содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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 the chrome.scripting API 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.json for 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!

Часто задаваемые вопросы

Урок «Внедрение контентных скриптов» бесплатный?

Да — полный текст урока «Внедрение контентных скриптов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Browser Extensions Development (Chrome & Edge), подпишись на CoddyKit PRO. Курс Browser Extensions Development (Chrome & Edge) содержит 4 уроков всего.

Чему я научусь в уроке «Внедрение контентных скриптов»?

Научитесь внедрять JavaScript и CSS в определённые веб-страницы, чтобы расширение могло изменять их внешний вид и поведение. Ты практикуешь Browser Extensions Development (Chrome & Edge) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Browser Extensions Development (Chrome & Edge)?

Предыдущий опыт не требуется. Browser Extensions Development (Chrome & Edge) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Внедрение контентных скриптов»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Browser Extensions Development (Chrome & Edge)?

Да. Каждый урок Browser Extensions Development (Chrome & Edge) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Внедрение контентных скриптов
  2. Изменение DOM веб-страницы
  3. Взаимодействие с данными веб-страницы
  4. Внедрение CSS и изолированное оформление
← Назад к Browser Extensions Development (Chrome & Edge)