Chrome API Explorer

The five APIs that turn an extension into a product. Read the snippet, then "run" a simulated version to see what each one does.

Query, create, update and move tabs. Needs no permission to create/update; reading URLs/titles needs "tabs" or a host match.

// find the active tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// open a new tab
chrome.tabs.create({ url: "https://example.com" });
// reload, then react when it finishes loading
chrome.tabs.reload(tab.id);
chrome.tabs.onUpdated.addListener((id, info) => {
  if (info.status === "complete") console.log("loaded");
});
— result —

Inject JS or CSS on demand. Needs "scripting" + host access (or activeTab).

// run a function in the page
await chrome.scripting.executeScript({
  target: { tabId },
  func: () => document.body.style.filter = "invert(1)",
});
// or inject a CSS file
await chrome.scripting.insertCSS({
  target: { tabId }, files: ["overlay.css"],
});
— page filter: none —
A pretend web page. Inject a script to invert its colors.

Add items to the right-click menu. Needs "contextMenus". Right-click the box below.

// create once, e.g. in onInstalled
chrome.contextMenus.create({
  id: "define", title: 'Define "%s"', contexts: ["selection"],
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "define") define(info.selectionText);
});
Select this text, then right-click to see the custom menu item.
Back
Reload
🔍 Define selection
— right-click the box —

Keyboard shortcuts. Declared in the manifest under commands; users can rebind them.

// manifest.json
"commands": {
  "toggle-feature": {
    "suggested_key": { "default": "Ctrl+Shift+Y" },
    "description": "Toggle the feature"
  }
}
// background.js
chrome.commands.onCommand.addListener((cmd) => {
  if (cmd === "toggle-feature") toggle();
});

Press Shift+Y anywhere on this page to fire the command:

— waiting for shortcut —

Rich OS notifications. Needs "notifications".

chrome.notifications.create("done", {
  type: "basic",
  iconUrl: "icon128.png",
  title: "Sync complete",
  message: "42 items updated.",
  buttons: [{ title: "View" }],
});
chrome.notifications.onButtonClicked.addListener((id, i) => { /* ... */ });
— no notification yet —
Titlemessage