Giter Site home page Giter Site logo

vocably / hermes Goto Github PK

View Code? Open in Web Editor NEW
7.0 1.0 0.0 326 KB

Typesafe browser extension messaging created with Typescript

License: MIT License

JavaScript 16.95% TypeScript 81.45% Shell 1.60%
chrome chrome-extension extension typescipt firefox firefox-extension promise safari safari-extension

hermes's Introduction

@vocably/hermes

npm package

A typesafe and promise-based messaging for the browser extension.

Supports Chrome, Firefox, and Safari.

Utilizes runtime.sendMessage, runtime.onMessage.addListener, and runtime.onMessageExternal.addListener.

Installation

npm install --save @vocably/hermes

API

The @vocably/hermes exports 2 methods: createMessage and createExternalMessage.

createMessage

createMessage could be used for messaging between content script and service worker when extension ID is not necessary.

const [messageSender, messageSubscriber] = createMessage<
  PayloadType,
  ResponseType
>('messageIdentifier');

messageSender function expects PayloadType as the only param. PayloadType could be void. Returns Promise<ResponseType>;

messageSubscriber function should be used in Service Worker to receive data of PayloadType, asynchronously process it, and return value of ResponseType.

createExternalMessage

createExternalMessage could be used for messaging between externally_connectable URLs and service worker when extension ID is necessary.

const [messageSender, messageSubscriber] = createExternalMessage<
  PayloadType,
  ResponseType
>('messageIdentifier');

messageSender function expects extensionId: string as the first parameter and PayloadType as the second. PayloadType could be void. Returns Promise<ResponseType>;

messageSubscriber function should be used in Service Worker to receive data of PayloadType, asynchronously process it, and return value of ResponseType.

Comprehensive Example

Let's imagine we need to create a user, pass it to a Service Worker and wait for the response from the Service Worker.

// save-user.ts

import { createMessage } from '@vocably/hermes';

type User = {
  id?: string;
  name: string;
  email: string;
};

type SaveUserResponse = {
  id: string;
};

export const [saveUser, onSaveUserRequest] = createMessage<
  User,
  SaveUserResponse
>('saveUser');
// content-script.ts

import { saveUser } from './save-user.ts';

saveUser({
  name: 'Speedy Gonzales',
  email: '[email protected]',
}).then(({ id }) => {
  console.log(`The saved user ID is ${id}`);
});
// sevice-worker.ts

import { onSaveUserRequest } from './save-user.ts';

onSaveUserRequest(async (sendResponse, user) => {
  let id: string;

  if (user.id) {
    // api.updateUser should be implemmented
    // individually. It's not a part of @vocably/hermes
    await api.updateUser(user);
    id = user.id;
  } else {
    // api.createUser should be implemmented
    // individually. It's not a part of @vocably/hermes
    id = await api.createUser(user);
  }

  // The callback function must return sendResponse() with the message return value passed into it.
  return sendResponse({
    id,
  });
});

hermes's People

Contributors

sneas avatar semantic-release-bot avatar

Stargazers

Casey Woolley avatar Gašper Dobrovoljc avatar Rail Batyrshin avatar Tom avatar  avatar Greg McCarthy avatar Hamza Kyamanywa avatar

Watchers

 avatar

hermes's Issues

Feature Request: Long-lived connections Support

Hi,

This library is excellent; using it has greatly improved the efficiency of developing.

Is there any plan support for long-lived connections?

Some scenarios require the use of long-lived connections.


https://developer.chrome.com/docs/extensions/develop/concepts/messaging#connect

// content-script.js:

var port = chrome.runtime.connect({name: "knockknock"});
port.postMessage({joke: "Knock knock"});
port.onMessage.addListener(function(msg) {
  if (msg.question === "Who's there?")
    port.postMessage({answer: "Madame"});
  else if (msg.question === "Madame who?")
    port.postMessage({answer: "Madame... Bovary"});
});

// background.js
chrome.runtime.onConnect.addListener(function(port) {
  console.assert(port.name === "knockknock");
  port.onMessage.addListener(function(msg) {
    if (msg.joke === "Knock knock")
      port.postMessage({question: "Who's there?"});
    else if (msg.answer === "Madame")
      port.postMessage({question: "Madame who?"});
    else if (msg.answer === "Madame... Bovary")
      port.postMessage({question: "I don't get it."});
  });
});

Feature Request: Long-lived connections Support

Hi,

This library is excellent; using it has greatly improved the efficiency of developing.

Is there any plan support for long-lived connections?

Some scenarios require the use of long-lived connections.


https://developer.chrome.com/docs/extensions/develop/concepts/messaging#connect

// content-script.js:

var port = chrome.runtime.connect({name: "knockknock"});
port.postMessage({joke: "Knock knock"});
port.onMessage.addListener(function(msg) {
  if (msg.question === "Who's there?")
    port.postMessage({answer: "Madame"});
  else if (msg.question === "Madame who?")
    port.postMessage({answer: "Madame... Bovary"});
});

// background.js
chrome.runtime.onConnect.addListener(function(port) {
  console.assert(port.name === "knockknock");
  port.onMessage.addListener(function(msg) {
    if (msg.joke === "Knock knock")
      port.postMessage({question: "Who's there?"});
    else if (msg.answer === "Madame")
      port.postMessage({question: "Madame who?"});
    else if (msg.answer === "Madame... Bovary")
      port.postMessage({question: "I don't get it."});
  });
});

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.