npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ext-messenger

v4.0.0

Published

Extension message passing made easy

Downloads

285

Readme

Browser Extension message passing made easy

Latest Stable Version NPM Downloads

What?

Small library for messaging across any browser extension parts (background, content script, popup or devtool).

It has a simple API, promise based callback support and more.

Supports extensions for Chrome and any Chromium based browser extensions like Edge, Arc, ...

Why?

Sending messages between extension parts can get complicated and usually requires some relaying mechanism in the background page. Adding callback functionality to these messages can make it even trickier.

Furthermore, the messaging API is not coherent or straight forward, sometimes requiring you to use runtime.* API and sometimes tabs.* API depending on which extension part you are currently in.

How?

npm i ext-messenger

OR

yarn add ext-messenger

1) In the background page: create a messenger instance and init the background hub

const Messenger = require('ext-messenger');
let messenger = new Messenger(Messenger.EXT_PARTS.BACKGROUND);

messenger.initBackgroundHub();

This step is obligatory and should be done as soon as possible in your background page.

* You can also add the library via script tag and use window['ext-messenger'].

2) Init connections (in any extension parts)

const Messenger = require('ext-messenger');
let messenger = new Messenger(Messenger.EXT_PARTS.CONTENT_SCRIPT);

/*
 * {string} name - Identifier name for this connection.
 * {function} messageHandler - Handler for incoming messages.
 */
messenger.initConnection(name, messageHandler);

This returns a connection object.

3) Start sending messages across connections (in any extension parts)

/*
 * {string} to - '<extension part>:<connection name>'.
 * {*} message - The message to send (any JSON-ifiable object).
 */
connection.sendMessage(to, message);
  • <extension part> possible values: background, content_script, popup, devtool.
  • Sending messages from background require an additional tab id argument :<tab id>.

Returns a Promise:

  • The promise will be resolved if the receiver invoked the sendResponse method argument (see example below).
  • The promise will be rejected if the connection has been disconnected via the disconnect() API.

More

// Init hub with handlers notifying someone connected/disconnected.
messenger.initBackgroundHub({
    connectedHandler: function(extensionPart, connectionName, tabId) {},
    disconnectedHandler: function(extensionPart, connectionName, tabId) {}
});

// Sending to multiple connections is supported via:
// 'extension part:name1,name2,...'.
c.sendMessage('content_script:main,main2', { text: 'HI!' });

// Sending to all connections is supported using wildcard value '*'.
c.sendMessage('devtool:*', { text: 'HI!' });

// Disconnect the connection to stop listening for messages.
c.disconnect();

When sending a message to multiple extension names (e.g. "name1,name2" or "*"), the returned promise will be resolved by the first connection that sends a response.

Example

/* ---------------------------------------------- */
/* Init connections in desired extension part:    */
/* BACKGROUND, CONTENT_SCRIPT, POPUP, DEVTOOL     */
/* ---------------------------------------------- */
const Messenger = require('ext-messenger');
let messenger = new Messenger(Messenger.EXT_PARTS.BACKGROUND);

let messageHandler = function(msg, from, sender, sendResponse) {
    if (msg.text === 'HI!') {
        sendResponse('HOWDY!');
    }
};

let c = messenger.initConnection('main', messageHandler);
let c2 = messenger.initConnection('main2', messageHandler);
...

let msg = { text: 'HI!' };

/* ------------------------------------------------------ */
/* Send message to content script                         */
/* ------------------------------------------------------ */
c.sendMessage('content_script:main', msg);

/* ------------------------------------------------------ */
/* Send message to popup (with response)                  */
/* ------------------------------------------------------ */
c.sendMessage('popup:main2', msg).then((response) => {
    console.log(response);
});

/* ------------------------------------------------------ */
/* Send message to background (with response)             */
/* ------------------------------------------------------ */
c.sendMessage('background:main', msg).then((response) => {
    console.log(response);
});

/* ------------------------------------------------------ */
/* Send message from background to devtool.               */
/* '50' is an example tab id of the devtool.              */
/* ------------------------------------------------------ */
c.sendMessage('devtool:main:50', msg).then((response) => {
    console.log(response);
});

Notes

  • Requires your extension to have "tabs" permission.
  • Uses only long lived port connections via runtime.* API.
  • This library should satisfy all your message passing needs, however if you are still handling some port connections manually, using runtime.onConnect will also receive messenger ports connections. In order to identify connections originating from this library you can use the static method Messenger.isMessengerPort(port) which will return true/false.
  • The Messenger messageHandler and runtime.onMessage similarities and differences:
    • Same - sender object.
    • Same - sendResponse - The argument should be any JSON-ifiable object.
    • Same - sendResponse - With multiple message handler, the sendResponse() will work only for the first one to respond.
    • Different - from object indicating the senders formatted identifier e.g. devtool:connection name.
    • Different - Async sendResponse is supported directly (no need to return true value like with runtime.onMessage).
  • This library should probably also work for Firefox extensions but have never been tested.
  • This library is compatible with manifest V3 (if you are looking for a manifest V2 compatible version, you can use version ^3.0.2).

Extensions using messenger

Developing Locally

npm install
npm run dev

You can now use the built messenger from the dist folder in a local test extension (or use npm link).

I have created one (for internal testing purposes) that you can use: ext-messenger-test.

License

MIT