### Installing Extension Bus with Alias via NPM (Bash) Source: https://github.com/davestewart/extension-bus/blob/main/README.md This command installs the extension-bus library but assigns it the alias 'bus'. This allows for shorter import statements in your code. ```Bash npm i bus@npm:@davestewart/extension-bus ``` -------------------------------- ### Installing Extension Bus via NPM (Bash) Source: https://github.com/davestewart/extension-bus/blob/main/README.md This command installs the extension-bus library using the npm package manager. This is the standard way to add the library to your project's dependencies. ```Bash npm i @davestewart/extension-bus ``` -------------------------------- ### Importing makeBus with Alias (TypeScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md This snippet shows how to import the makeBus function when the extension-bus library was installed using the 'bus' alias via npm. ```TypeScript // easier import import { makeBus } from 'bus' ``` -------------------------------- ### Demonstrating Extension Bus Error Codes (JavaScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md Provides examples of how different call targets (`*` for multiple listeners vs a named bus) can result in different error codes (`no_response` vs `no_handler`) when no matching handler is found, illustrating the behavior when targeting single vs multiple buses. ```JavaScript await bus.call('*:unknown') || bus.error?.code // 'no_response' await bus.call('background:unknown') || bus.error?.code // 'no_handler' ``` -------------------------------- ### Calling Various Targets from Background Script (JS) Source: https://github.com/davestewart/extension-bus/blob/main/README.md Demonstrates how to use `bus.call` and `bus.callTab` from the background script to communicate with different parts of the extension or specific tabs. Includes examples for calling all processes, pages, popups, and targeting the active tab using Chrome API. ```js // call all processes await bus.call('pass', 'hello from background') // call an open page function await bus.call('page:pass', 'hello from background') || bus.error // call an open page function that fails await bus.call('page:fail', 'hello from background') || bus.error // call popup (if open) await bus.call('popup:pass', 'hello from background') || bus.error // target a content script // reload any tab and check the console for the tab id, e.g. 334068351 await bus.callTab(334068351, 'pass') // set active tab's body color to red (must be an https:// page) chrome.windows.getLastFocused(function (window) { chrome.tabs.query({ active: true, windowId: window.id }, async function (tabs) { const [tab] = tabs const result = await bus.call(tab.id, 'update', 'red') console.log(result) }) } ``` -------------------------------- ### Messaging Another Extension from Background (TS/JS) Source: https://github.com/davestewart/extension-bus/blob/main/README.md Shows how to use `bus.callExtension` from the background script to send a message to another installed extension. Note that only specific paths (`pass`, `nested/hello`) might be exposed externally. ```ts const result = await bus.callExtension('', 'pass') ``` -------------------------------- ### Sending Messages to Other Processes (JavaScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md These snippets illustrate different ways to call handlers on buses in other processes using the bus.call() method. Examples include calling a flat handler, a nested handler using '/' syntax, and overriding the default target process. ```JavaScript // flat const result = await bus.call('greet', 'hello') ``` ```JavaScript // nested const result = await bus.call('foo/bar/baz', payload) ``` ```JavaScript // override target const result = await bus.call('popup:greet', 'hello') ``` -------------------------------- ### Handling Call Errors in Content Script (JS) Source: https://github.com/davestewart/extension-bus/blob/main/README.md Illustrates how to handle errors when calling a bus function from a content script using the `.catch()` method. The example shows catching a `BusError` and logging its details. ```js bus.call('fail').catch((err: BusError) => { console.log('Error:', err) }) ``` -------------------------------- ### Configuring External Message Reception - TypeScript Source: https://github.com/davestewart/extension-bus/blob/main/README.md Explains how to configure an Extension Bus instance to receive messages from web pages or other extensions. It shows examples of accepting all external messages, accepting messages only to specific paths (with wildcards), and using a predicate function for programmatic control based on sender and path. ```TypeScript const bus = makeBus('background', { // always accept messages external: true, // accept calls only to these paths (supports wildcards) external: [ 'account/login', 'user/*', ], // programatically accept messages external (path: string, sender: chrome.runtime.MessageSender): boolean { return sender.tab.url.startsWith('https://yourdomain.com') && path.startsWith('account/') }, }) ``` -------------------------------- ### Sending Message from Non-Extension Bus Extension - JavaScript Source: https://github.com/davestewart/extension-bus/blob/main/README.md Provides an example of how a standard browser extension can send a message to an Extension Bus extension using `chrome.runtime.sendMessage`. It shows the required message format (`path` and optional `data`) and handling the response. ```JavaScript chrome.runtime.sendMessage('', { path: 'path/to/handler', data: 123 }, function (response) { if (response) { console.log(response.result) } }) ``` -------------------------------- ### Creating and Configuring an Extension Bus (JavaScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md This code demonstrates how to create a new bus instance for a specific process (e.g., 'popup'). It shows how to optionally set a default target process, define handler functions for incoming messages, and enable external connections. ```JavaScript import { makeBus } from 'extension-bus' // named process const bus = makeBus('popup', { // optionally target a specific process target: 'background', // handle incoming requests handlers: { foo (value, sender) { ... }, bar (value, { tab }) { ... }, }, // allow external connection external: true, }) ``` -------------------------------- ### Configure MV3 Background Script in manifest.json Source: https://github.com/davestewart/extension-bus/blob/main/README.md This JSON snippet shows how to configure the 'background' key in the manifest.json file specifically for running the MV3 demo in Firefox. It specifies the background script file location. ```json { "background": { "scripts": [ "app/background/background.js" ] } } ``` -------------------------------- ### Calling Handler with Extension Bus (TypeScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md This snippet demonstrates the basic syntax for calling a registered handler on the bus. It shows how to await the result of the asynchronous call, passing a handler path and an optional payload. ```TypeScript const result = await bus.call('some/handler', payload) ``` -------------------------------- ### Configuring Extension Bus Error Handling (JavaScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md Shows different ways to configure the `onError` option when creating an Extension Bus instance using `makeBus`. Options include 'warn' (default), 'reject' to throw an error, or providing a custom function for flexible error handling. ```JavaScript const bus = makeBus('popup', { // warns in the console (unless error is "no_response") and returns null onError: 'warn', }) ``` ```JavaScript const bus = makeBus('popup', { // rejects a BusError object, and should be handled by try/catch or .catch(err) onError: 'reject', }) ``` ```JavaScript const bus = makeBus('popup', { // custom function, from which you can return a value onError: (request: BusRequest, response: BusResponse, error: Bus) => { ... }, }) ``` -------------------------------- ### Calling Extension Bus Handler (Content Script) - TypeScript Source: https://github.com/davestewart/extension-bus/blob/main/README.md Demonstrates how to call a registered handler on the Extension Bus from a content script. It shows awaiting the result of the call. ```TypeScript // content script const result = await bus.call('bookmarks/related', 'www.google.com') ``` -------------------------------- ### Sending Messages to Other Extensions (JavaScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md This snippet demonstrates how to use the bus.callExtension() method to send messages to a bus instance running in a different web extension, identified by its extension ID. ```JavaScript const result = await bus.callExtension('', 'account/login', { username, password }) ``` -------------------------------- ### Defining Extension Bus Handlers (Background Script) - TypeScript Source: https://github.com/davestewart/extension-bus/blob/main/README.md Shows how to define handlers for the Extension Bus in a background script. It illustrates using the `Handlers` type for sender context typing, accessing sender properties (like `tab`), referencing sibling handlers using `this`, and returning a value to the caller. ```TypeScript import { type Handlers } from 'extension-bus' // Use the Handlers type to automatically type the `sender` property const handlers: Handlers = { bookmarks: { async related (domain: string, { tab }) { // 1️⃣ reference sender if (tab.url?.includes(domain)) { // 2️⃣ reference sibling handlers const bookmarks = await this.search(domain) // 3️⃣ optionally return a value return { bookmarks } } }, search (domain: string) { return chrome.tabs.query({ url: `https://${domain}/*` }) } } } ``` -------------------------------- ### Typing Extension Bus Handlers (TypeScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md This snippet shows how to use the Handlers type from extension-bus to provide type safety for your handler functions. It demonstrates typing the value parameter and accessing properties from the sender object. ```TypeScript import { type Handlers } from 'extension-bus' export const handlers: Handlers = { // number, chrome.runtime.MessageSender foo (value: number, { tab }) { const url = tab?.url } } ``` -------------------------------- ### Checking Extension Bus Error State (JavaScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md Demonstrates how to check for an error after an Extension Bus call by inspecting the `bus.error` property if the call result is `null`. This allows for specific error handling logic. ```JavaScript const result = await bus.call('foo/bar') if (result === null && bus.error) { // handle error } ``` -------------------------------- ### Typing Call Results and Payloads (TypeScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md This snippet shows how to provide type parameters to the bus.call() method to specify the expected type of the result and the payload being sent, enhancing type safety. ```TypeScript const window = await bus.call('windows/get', 1) ``` -------------------------------- ### Typing Calls with Potential Null Results (TypeScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md This snippet demonstrates how to use a union type (e.g., Window | null) for the result type when a call might not complete successfully (e.g., target tab closed). This allows for checking the result before using it. ```TypeScript const window = await bus.call('windows/get', 1000) if (window) { ... } ``` -------------------------------- ### Sending Messages to Other Tabs (JavaScript) Source: https://github.com/davestewart/extension-bus/blob/main/README.md These snippets show how to use the bus.callTab() method to send messages specifically to content scripts running in browser tabs. You can target a specific tab by ID or the current tab using 'true'. ```JavaScript // call a specific tab const result = await bus.callTab(123, 'greet', 'hello') ``` ```JavaScript // call the current tab (useful from the extension's action icon) const result = await bus.callTab(true, 'greet', 'hello') ``` -------------------------------- ### Extension Bus Error Object Structure (JSON) Source: https://github.com/davestewart/extension-bus/blob/main/README.md Shows the structure of the error object available in the `bus.error` property when an error occurs during an Extension Bus call. It includes the error code, message, and target of the failed call. ```JSON { "code": "handler_error", "message": "foo is not defined", "target": "background:foo/bar" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.