Chrome Extension Helper
A helper library to streamline the development of Chrome extensions using React. This package provides utilities for handling context menus, injecting React components into the DOM, and managing messages between Chrome tabs.
Installation
Install the package with npm or yarn:
npm install chrome-extension-helper
yarn add chrome-extension-helper
Getting Started
Define custom context menus with the addContextMenu
function:
import { addContextMenu } from 'chrome-extension-helper';
addContextMenu('MY_ACTION', 'My Action Title', { contexts: ['all'] });
2. Injecting React Components
Easily inject React components into the DOM with the injectReact
function:
import { injectReact } from 'chrome-extension-helper';
import MyComponent from './MyComponent';
injectReact({
id: 'my-react-component',
component: <MyComponent />,
css: true,
cssString: '.my-class { color: blue; }',
fontUrl: 'https://fonts.googleapis.com/css2?family=Roboto&display=swap',
});
3. Removing Injected React Components
Remove injected components with the removeReact
function:
import { removeReact } from 'chrome-extension-helper';
removeReact('my-react-component');
4. Sending Messages
Communicate between Chrome tabs and the background script using sendChromeMessage
:
import { sendChromeMessage } from 'chrome-extension-helper';
sendChromeMessage({
type: 'MY_ACTION',
data: { foo: 'bar' },
callback: (tabs, response) => console.log('Response:', response),
});
5. Setting Up Background Scripts
Use setupBackgroundExtension
to register context menus and listeners in the background script:
import { setupBackgroundExtension } from 'chrome-extension-helper';
setupBackgroundExtension([{ id: 'MY_ACTION', title: 'My Action Title' }]);
6. Setting Up Content Scripts
Configure message listeners with setUpContentExtension
:
import { setUpContentExtension } from 'chrome-extension-helper';
setUpContentExtension([
{
action: 'MY_ACTION',
callback: ({ data, sendResponse }) => {
console.log('Received data:', data);
sendResponse({ success: true });
},
},
]);
7. Keyboard-Controlled Component Removal
Easily unmount components with a specified key using the useRemoveReact
hook:
import useRemoveReact from 'chrome-extension-helper';
const { onClose } = useRemoveReact('my-react-component', { keyCode: 'Escape' });
Types
This library provides the following TypeScript types for ease of use:
ChromeMessage<T>
: Represents a message sent between Chrome tabs.ChromeActionConfig
: Configuration for actions handled in content scripts.ChromeContextMenuConfig
: Configuration for custom context menus.