Coder Social home page Coder Social logo

p3ol / buddy Goto Github PK

View Code? Open in Web Editor NEW
8.0 3.0 0.0 9.2 MB

๐Ÿ• Dead simple cross-domain iframe/window messaging

License: MIT License

JavaScript 34.33% TypeScript 65.67%
popup-messaging popup-windows popup post-messaging iframe promise post-message

buddy's Introduction

CI

๐Ÿ• Buddy

Dead simple cross-domain iframe messaging

Installation

yarn add @poool/buddy

Usage

import { on, send } from '@poool/buddy';

// Register handler inside child window
on('getInfos', async event => {
  console.log('You have a message from some window :', event.data);

  // You can even pass methods to child window and retrieve its return value
  // using promises or async/await:'
  console.log(await event.data.someMethod());

  // You can even send data back to parent, EVEN METHODS \o/
  // Parent will only have to await `send()` method promise to get the result
  return { someOtherMethod: () => 30 };
}, { source: someParentWindow });

// And send some message from parent window
send(someChildWindow, 'getInfos', { infos: 'some string', someMethod: () => 25 }, { origin: '*' });

Buddy serializes all the primitive types (using JSON.parse) and even methods, using custom back & forth Promise logic.

Configuration

Global options can be updated using setGlobalOptions method:

import { setGlobalOptions } from '@poool/buddy';

setGlobalOptions({ logLevel: 0 });

Options

timeout

  • Type: Number
  • Default: 5000

Message expiration time, after which an error will be thrown.

logLevel

  • Type: Number
  • Default: 1

Either 0 (disabled), 1 (error), 2 (warn), 3 (info), 4 (debug), 5 (log)

queue

  • Type: Boolean
  • Default: false

If true, messages will be queued until the target window is ready to receive them. Needs to also be set inside the target window to trigger a ready event.

serializers

  • Type: Array<BuddySerializer>
  • Default: []

Custom serializers to use to serialize/unserialize data. See serializers section for more details.

Documentation

on(name, callback, options)

  • name {String} Event name
  • callback {Function}
    • event {Object}
  • options {Object}
    • source {Window} Source window
    • origin {String} Origin expected from source window. * (default) or any other origin.
    • ...globalOptions

send(target, name, data, options)

  • target {Window} Target window
  • name {String} Event name
  • data {Object} Data to be serialized & sent to child
  • options {Object}
    • origin {String} Origin expected from source window. * (default) or any other origin.
    • pingBack {Boolean} Mostly used internally. Whether sender should await a response from receiver or not. true (default) or false
    • ...globalOptions

Custom serializers

Buddy uses JSON.stringify to send pre-serialized data to .postMessage (and JSON.parse to deserialize), allowing to automatically serialize primitive data like numbers or strings, and uses internal serializers to pre-serialize more complex data like Date, Error or even Function and Promise objects.

Although it cannot cover all the possible use cases, you can add your own serializers to handle custom data types. A serializer is a simple object with four methods: serializable, serialize, unserializable and unserialize.

// Creating a custom serializer for Map objects
const mapSerializer = {
  serializable: data => data instanceof Map,
  serialize: data => ({ type: 'map', entries: Array.from(data.entries()) }),
  unserializable: data => data.type === 'map' && data.entries,
  unserialize: data => new Map(data.entries),
};

โš ๏ธ A custom serializer's serializable/unserializable methods returning true for any data will override all the other serializers, even internal ones, so be careful to only match the data you specifically want to serialize.

Contributing

Please check the CONTRIBUTING.md doc for contribution guidelines.

Development

Install dependencies:

yarn install

Run examples at http://localhost:64000/ with webpack dev server:

yarn serve

And test your code:

yarn test

License

This software is licensed under MIT.

buddy's People

Contributors

auto-update-cop[bot] avatar dackmin avatar dependabot[bot] avatar nicolasauger avatar renovate-bot avatar renovate[bot] avatar yannispgs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

buddy's Issues

Correctly handle non error promise rejections

If I want buddy to fail correctly when sending a promise that should fail when called:

send(child, 'test', {
  do: async thing => {
    // Throw something that is not an Error instance
    throw thing;
  },
});

I currently have to transform that something to a real instance of Error so buddy treats it as an error and not a valid promise result:

send(child, 'test', {
  do: async thing => {
    throw thing instanceof Error ? thing : new Error(thing);
  },
});

We should probably better handle thrown expressions that are not real Error instances.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (p3ol/renovate-presets//presets/base#v1.0.0)

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm standard-version Available

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update github/codeql-action action to v3
  • chore(deps): replace dependency standard-version with commit-and-tag-version 9.5.0
  • chore(deps): update dependency rollup-plugin-dts to v6.1.1
  • chore(deps): update dependency tslib to v2.6.3
  • chore(deps): update eslint monorepo (@typescript-eslint/eslint-plugin, @typescript-eslint/parser, eslint, eslint-plugin-import, eslint-plugin-n, eslint-plugin-promise)
  • chore(deps): update webpack monorepo (html-webpack-plugin, webpack, webpack-dev-server)
  • chore(deps): update dependency @rollup/plugin-commonjs to v26
  • chore(deps): update dependency jest-dev-server to v10
  • chore(deps): update dependency nyc to v17
  • chore(deps): update dependency puppeteer to v23
  • chore(deps): update dependency sinon to v18
  • chore(deps): update dependency webpack-dev-server to v5
  • chore(deps): update eslint monorepo (major) (@typescript-eslint/eslint-plugin, @typescript-eslint/parser, eslint, eslint-plugin-n, eslint-plugin-promise)
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/setup-node v4
  • codecov/codecov-action v4.5.0
.github/workflows/codeql-analysis.yml
  • actions/checkout v4
  • github/codeql-action v2
  • github/codeql-action v2
  • github/codeql-action v2
npm
package.json
  • @babel/eslint-plugin 7.22.10
  • @poool/eslint-config 3.0.1
  • @poool/eslint-plugin 3.0.0
  • @rollup/plugin-commonjs 25.0.7
  • @rollup/plugin-node-resolve 15.2.3
  • @rollup/plugin-swc 0.3.0
  • @rollup/plugin-terser 0.4.4
  • @rollup/plugin-typescript 11.1.5
  • @swc/core 1.3.96
  • @swc/jest 0.2.29
  • @typescript-eslint/eslint-plugin 6.11.0
  • @typescript-eslint/parser 6.11.0
  • eslint 8.53.0
  • eslint-config-standard 17.1.0
  • eslint-plugin-import 2.29.0
  • eslint-plugin-n 16.3.1
  • eslint-plugin-promise 6.1.1
  • html-webpack-plugin 5.5.3
  • jest 29.7.0
  • jest-dev-server 9.0.1
  • nyc 15.1.0
  • puppeteer 21.5.2
  • puppeteer-to-istanbul 1.4.0
  • rollup 4.4.1
  • rollup-plugin-dts 6.1.0
  • sinon 17.0.1
  • standard-version 9.5.0
  • swc-loader 0.2.3
  • tslib 2.6.2
  • typescript 5.2.2
  • webpack 5.89.0
  • webpack-cli 5.1.4
  • webpack-dev-server 4.15.1
  • node >=16
  • yarn 4.0.2

  • Check this box to trigger a request for Renovate to run again on this repository

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.