Skip to content

Chrome Extension API Introduction

eupthere edited this page Dec 15, 2025 · 1 revision

들어가며

Chrome의 Extension API는 브라우저의 기능을 확장하거나 일부 동작에 개입하기 위한 도구이다. 일반적인 웹 페이지에서 접근 가능한 Web API에 포함되지 않은, 탭 관리, 네트워크 요청 제어 등 브라우저 수준의 기능을 제공한다. Mozilla는 Chrome 확장 모델을 기반으로, 다른 브라우저(Firefox, Microsoft Edge, Opera 등)와의 호환성을 높이기 위해 WebExtensions API를 도입했다. 다만 WebExtensions는 절대적인 표준은 아니므로, 브라우저마다 제공되는 API와 동작에는 차이가 있다. 이 글에서는 Chrome 기준 Extension API만 다룬다.

자료 출처: Chrome Extensions → Develop

아래 기록에서는 출처에서 나열된 기능 소개을 간략히 번역하고, 관련 코드를 찾아 예시로 제시함.
아래 읽기 전 확인하면 좋은 내용

무엇이 가능한가?

Override Chrome Pages And Settings

Settings overrides are a way for extensions to override selected Chrome settings. Additionally, extensions can use HTML override pages to replace a page Google Chrome normally provides. An extension can override the bookmark manager, the history tab, or the new tab.

Chrome에서 기본적으로 제공하는 페이지를 오버라이드 할 수 있다 (설정, 북마크, 히스토리, 새 탭 등). 확장 프로그램 예시: 기본 설정 페이지를 '대체'한다 (수정 및 확장 아님).

manifest.json"chrome_url_overrides" 필드 참고.

manifest: Every extension must have a manifest.json file in its root directory that lists important information about the structure and behavior of that extension. This page explains the structure of extension manifests and the features they can include.

manifest는 확장프로그램의 구조와 행동에 대해 나열함.

{
  "manifest_version": 3,
  "name": "History Override",
  "description": "Demonstrates how to override the default history page.",
  "version": "1.0",
  "chrome_url_overrides": {
    "history": "history.html"
  },
  "permissions": ["history", "favicon"],
  "icons": {
    "16": "history16.png",
    "32": "history32.png",
    "48": "history48.png",
    "128": "history128.png"
  }
}

Extending Devtools

DevTools extensions add functionality to Chrome DevTools by accessing DevTools-specific extension APIs through a DevTools page added to the extension. You can also use the chrome.debugger API to invoke Chrome's remote debugging protocol. Attach to one or more tabs to instrument network interaction, debug JavaScript, mutate the DOM, and more.

개발자 도구에 기능을 추가할 수 있다. chrome.debugger를 사용하는 확장 프로그램 예시: 네트워크의 트래픽을 듣는다.

chrome.debugger.onEvent.addListener(function (source, method, params) {
  if (method === 'Network.responseReceived') {
    console.log('Response received:', params.response);
    // Perform your desired action with the response data
  }
});

Display Notifications

The chrome.notifications API lets you create notifications using templates and show these notifications to users in the user's system tray.

system tray: OS 수준에서 제공하는 알림. 예) MacOS의 Notification Center.

시스템 트레이 알림을 보낼 수 있다. 확장 프로그램 예시: basic, progress, list 세 가지 알림 예시. MacOS에서는 progress bar가 표시되지 않고, list의 경우 첫 번째 항목만 표시된다고 함. Chrome 시스템 알림이 켜져 있어야 동작함 (MacOS 기준 System Settings → Notifications → Google Chrome → Allow Notifications). 꺼져 있으면 버튼 눌러도 조용히 실패함. Extension API로는 MacOS에서 Google Chrome 알림이 켜져 있는지 확인할 방법이 없어 보임. 설정을 켜야 된다는 안내 문구를 사용자에게 잘 보여줘야 될 듯.

basic.addEventListener('click', () => {
let options = {
  type: 'basic',
  title: 'Basic Notification',
  message: 'This is a Basic Notification',
  iconUrl: 'icon.png'
};
chrome.notifications.create(options);
});

Manage History

Use the chrome.history API to interact with the browser's record of visited pages, and the chrome.browsingData API to manage other browsing data. Use chrome.topSites to access the most visited sites.

히스토리와 상호작용할 수 있다. 확장 프로그램 예시: 히스토리를 검색하고 삭제하는 로직 구현되어 있음.

const historyItems = await chrome.history.search({
  text: searchQuery,
  startTime: kOneWeekAgo
});
clone
  .querySelector('.removeButton, button')
  .addEventListener('click', async function () {
	await chrome.history.deleteUrl({ url: item.url });
	location.reload();
  });

Control Tabs And Windows

Use APIs such as chrome.tabs, chrome.tabGroups and chrome.windows to create, modify, and arrange the user's browser.

탭, 탭 그룹, 윈도우와 상호작용할 수 있다. 생성 및 조작하고 옮길 수 있다. 확장 프로그램 예시: 구글 크롬 개발 관련 문서 탭을 그룹으로 묶어줌.

const tabs = await chrome.tabs.query({
  url: [
    'https://developer.chrome.com/docs/webstore/*',
    'https://developer.chrome.com/docs/extensions/*'
  ]
});

chrome.tabs.query: 현재 열려 있는 탭 중에 조건에 맞는 탭 목록을 조회. 위 예시에서는 URL을 기준으로 필터링.

element.querySelector('a').addEventListener('click', async () => {
  // need to focus window as well as the active tab
  await chrome.tabs.update(tab.id, { active: true });
  await chrome.windows.update(tab.windowId, { focused: true });
});
button.addEventListener('click', async () => {
  const tabIds = tabs.map(({ id }) => id);
  if (tabIds.length) {
    const group = await chrome.tabs.group({ tabIds });
    await chrome.tabGroups.update(group, { title: 'DOCS' });
  }
});

.update() 메서드로 tabs, windows, tabGroups 상태를 변경하는 예시.

Add Keyboard Shortcuts

Use the chrome.commands API to add keyboard shortcuts that trigger actions in your extension. For example, you can add a shortcut to open the browser action or send a command to the extension.

키보드 단축키 추가 가능. 확장 프로그램 예시: 탭 전환 단축키를 추가함.

manifest.jsoncomands 정의하고 chrome.commands에서 사용.

"commands": {
  "flip-tabs-forward": {
    "suggested_key": {
      "default": "Ctrl+Shift+Right",
      "mac": "Command+Shift+Right"
    },
    "description": "Flip tabs forward"
  },
  "flip-tabs-backwards": {
    "suggested_key": {
      "default": "Ctrl+Shift+Left",
      "mac": "Command+Shift+Left"
    },
    "description": "Flip tabs backwards"
  }
},
chrome.commands.onCommand.addListener(async (command) => {
// ...
  if (command === 'flip-tabs-forward') {
    newIndex = activeIndex === lastTab ? 0 : activeIndex + 1;
  }
// ...
}

Authenticate Users

Use the chrome.identity API to get OAuth 2.0 access tokens.

OAuth access token을 가져올 수 있다. 확장 프로그램 예시:

{
  "name": "Identity API Sample",
  "version": "4.0",
  "manifest_version": 3,
  "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDJB6ZGcGxtlr/34s+TKgi84QiP7DMekqOjSUS2ubmbhchlM6CN9gYdGQ1aBI3TBXG3YaAu+XyutFA8M8NLLWc4OOGByWaGV11DP6p67g8a+Ids/gX6cNSRnRHiDZXAd44ATxoN4OZjZJk9iQ26RIUjwX07bzntlI+frwwKCk4WQIDAQAB",
  "action": {},
  "background": {
    "service_worker": "main.js"
  },
  "permissions": ["identity", "identity.email"],
  "oauth2": {
    "client_id": "497291774654.apps.googleusercontent.com",
    "scopes": ["https://www.googleapis.com/auth/userinfo.profile"]
  }
}

Declare permissions: 확장 프로그램이 무엇을 하려고 하는지 permission에 표현해야 한다.

Permissions list

"identity": Gives access to the chrome.identity API.

"identity.email": Gives access to the user's email address through the chrome.identity API. Warning displayed: Know your email address.

chrome.identity
  .getAuthToken({ interactive: true })
  .then((token) => {
	displayOutput('Token acquired:\n' + token.token);
	changeState(STATE_AUTHTOKEN_ACQUIRED);
  })
  .catch((error) => {
	displayOutput(error.message);
	changeState(STATE_START);
  });

This extension uses the getAuthToken flow of the Identity API, so it only works with Google accounts. If you want to identify the user in a non-Google OAuth2 flow, you should use the launchWebAuthFlow method instead.

구글 계정 기반이 아닌 OAuth2도 launchWebAuthFlow로 구현 가능하다.

getAuthToken: Gets an OAuth2 access token using the client ID and scopes specified in the oauth2 section of manifest.json.

launchWebAuthFlow: This method enables auth flows with non-Google identity providers by launching a web view and navigating it to the first URL in the provider's auth flow.

Manage Extensions

The chrome.management API provides ways to manage the list of extensions that are installed and running. It is particularly useful for extensions that override the built-in New Tab page.

설치되어 실행중인 확장프로그램을 관리할 수 있다. 확장 프로그램 예시: 두더지 잡기 게임. 각 두더지가 하나의 확장 프로그램임. 게임 플레이 영상. Repository 내부의 mole 폴더는 두더지 확장 프로그램을 정의. controller 폴더는 여러 두더지 확장 프로그램들과 message를 주고 받으며 게임 로직 구현.

Each icon in the browser toolbar is a seperate extension. The extensions communicate using the chrome.runtime.sendMessage API and the chrome.runtime.onMessageExternal event.

// controller 코드
chrome.alarms.onAlarm.addListener(async () => {
  const extensions = await chrome.management.getAll();
  const moles = extensions.filter((e) => e.name === 'mole');

  const randomIndex = Math.floor(Math.random() * moles.length);

  chrome.runtime.sendMessage(moles[randomIndex].id, { id: chrome.runtime.id });
});
// mole 코드

// 두더지 잡히면 controller에 알림
chrome.action.onClicked.addListener(() => {
  if (!moleShowing) return;

  chrome.runtime.sendMessage(controllerId, 'success');
  hideMole();

  failTimeout && clearTimeout(failTimeout);
  failTimeout = undefined;
});

// 두더지 보여주라는 알림 들어오면 컨트롤러를 기억해두고(나중에 답장 보내기 위함), 두더지를 잠시 보여줌
chrome.runtime.onMessageExternal.addListener((msg) => {
  controllerId = msg.id;
  showMole();
  failTimeout = setTimeout(async () => {
    hideMole();
    const tabs = await chrome.tabs.query({});

    if (tabs.length > 0) {
      // const tabToClose = Math.floor(Math.random() * tabs.length);
      // chrome.tabs.remove(tabs[tabToClose].id);
    }
  }, 2000);
});

chrome.management.getAll()로 확장 프로그램 목록을 가져와 두더지에게 메시지를 보낸다. 각 확장 프로그램은 분리된 context에서 실행되기 때문에 message로 정보를 주고 받음.

Provide Suggestions

The chrome.omnibox API allows you to register a keyword with Google Chrome's omnibox (address bar).

확장 프로그램 예시: 검색 쿼리를 만들어주는 기능

When the user enters your extension's keyword, the user starts interacting solely with your extension. Each keystroke is sent to your extension, and you can provide suggestions in response.

manifest.json에 키워드 등록

"omnibox": { "keyword": "newTab" },

확장프로그램에서 받은 입력을 처리

// This event is fired with the user accepts the input in the omnibox.
chrome.omnibox.onInputEntered.addListener((text) => {
  // Encode user input for special characters , / ? : @ & = + $ #
  const newURL = 'https://www.google.com/search?q=' + encodeURIComponent(text);
  chrome.tabs.create({ url: newURL });
});

주소창에 newTab입력하면 자동 완성 창에 Omnibox - New Tab Search 확장프로그램 표시됨 → 선택하면 해당 확장프로그램과 상호작용 → 구글 쿼리를 붙여 새로운 탭을 만들어줌.

Update Chrome Settings

Use the chrome.privacy API to control usage of features in Chrome that can affect a user's privacy. Also see the chrome.proxy API to manage Chrome's proxy settings.

사용자 개인정보 보호 관련 기능 제어 가능하다. 확장 프로그램 예시: 신용카드 정보 자동완성 설정

chrome.runtime.onInstalled.addListener(() => {
  // Set default value for credit card autofill enabled
  chrome.privacy.services.autofillCreditCardEnabled.set({ value: true });
  updateAutofillEnabledStatus();
});

Manage Downloads

Use the chrome.downloads API to programmatically initiate, monitor, manipulate, and search for downloads.

manifest.json"downloads" 권한 필요.

"permissions": [
  "downloads"
],

확장 프로그램 예시: 다운로드 관련 rule을 정의하여 download를 중간에 가로채 작업할 수 있음. 예) 파일 이름 자동 변경, 덮어쓸 것인지 자동 결정, etc.

chrome.downloads.onDeterminingFilename.addListener(function(item, __suggest) {
  // ...
}

onDeterminingFilename: During the filename determination process, extensions will be given the opportunity to override the target DownloadItem.filename.

onChanged, onCreated, onDeterminingFilename, onErased 등 다양한 시점에서 다운로드 관련 작업을 가로채 함수를 실행할 수 있음.

Use Bookmarks And The Reading List

Use the chrome.bookmarks API and the chrome.readingList API to create, organize, and otherwise manipulate these lists.

확장 프로그램 예시: 북마크 추가, 검색, 삭제

// Add a bookmark for www.google.com
function addBookmark() {
  chrome.bookmarks.create(
    {
      title: 'Google',
      url: 'https://www.google.com'
    },
    () => {
      console.log('Bookmark added');
      location.reload(); // Refresh the popup
    }
  );
}

// Remove the bookmark for www.google.com
function removeBookmark() {
  chrome.bookmarks.search({ url: 'https://www.google.com/' }, (results) => {
    for (const result of results) {
      if (result.url === 'https://www.google.com/') {
        chrome.bookmarks.remove(result.id, () => {});
      }
    }
    location.reload();
  });
}

Clone this wiki locally