Lightweight (zero dependencies) library for enabling cross document web messaging on top of the MessageChannel API.

Overview

npm version

cross-document-messenger

Lightweight (zero dependencies) library for enabling cross document web messaging on top of the MessageChannel API.

API:

The API includes two connectors, one for the host app (HostConnector) and another for the hosted app loaded from the iframe (TargetFrameConnector).

Both connectors when initialized expose the CrossDocMessenger friendly api (emit, subscribe, unsubscribe) to be used by your application.

The Hosting application:

  • HostConnector
    • getInstance(): HostConnector
    • messenger (target: HTMLIFrameElement | undefined, targetOrigin: string): CrossDocMessenger ;

How to use:

  • Get the HostConnector instance statically by calling HostConnector.getInstance() or use the new keyword.
  • Init the messaging facade by invoking the messenger(...) method, passing required iframe params.
  • Start using the messenger API:
    • push messages to the iframe by: messenger.emit(...)
    • register messages from the iframe by: messenger.subscribe((m) => {...})
    • reset the connector by: messenger.unsubscribe()

Examples:

Recommended Angular way:

  1. Create a proxy service around HostConnector to be injected using Angular DI.
@Injectable({ providedIn: 'any' })
export class CrossDocumentMessengerService<T> {

  private readonly _connector: HostConnector;
  get connector(): HostConnector {
    return this._connector;
  }

  public messenger(target: HTMLIFrameElement | undefined, targetOrigin: string): CrossDocMessenger<T> {
    return this._connector.messenger(target, targetOrigin);
  }
  
  constructor() {
    this._connector = HostConnector?.getInstance();
  }
}
  1. Setup the target wrapper component to consume the instance of the service (you may have more than one iframe integrated into your app)
`, styleUrls: ['./wrapper.component.scss'], providers: [CrossDocumentMessengerService] }) .... private messenger: CrossDocMessenger ; constructor(private cdms: CrossDocumentMessengerService ) {} onLoad() { if (this.iframe?.nativeElement) { const targetOrigin = 'http://localhost:3000'; this.messenger = this.cdms?.messenger(this.iframe?.nativeElement, targetOrigin); this.messenger?.subscribe((data) => this.subscribeToChildMessages(data)); this.messenger.emit({ type: 'connected', data: 'initiated' }); } } ">
@Component({
  selector: 'app-wrapper',
  template: ` 
    
`
, styleUrls: ['./wrapper.component.scss'], providers: [CrossDocumentMessengerService] }) .... private messenger: CrossDocMessenger<any>; constructor(private cdms: CrossDocumentMessengerService<T>) {} onLoad() { if (this.iframe?.nativeElement) { const targetOrigin = 'http://localhost:3000'; this.messenger = this.cdms?.messenger(this.iframe?.nativeElement, targetOrigin); this.messenger?.subscribe((data) => this.subscribeToChildMessages(data)); this.messenger.emit({ type: 'connected', data: 'initiated' }); } }

The Hosted application:

  • TargetFrameMessenger - import TargetFrameMessenger to get the CrossDocMessenger functionalities over the initialized TargetFrameConnector instance.

  • Start using the messenger API:

    • Emit messages to the host by: messenger.emit(...)
    • Subscribe to the host's messages by: messenger.subscribe((m) => {...})
    • Detach the native event listener and clear the connector state by: messenger.unsubscribe()

Examples:

Hosted React application:

Subscribing to host's messages on component mount and unsubscribing when unmount

{ useEffect(() => { messenger.subscribe((e: Message ) => { }) return () => { messenger.unsubscribe(); } }, []) ..... const handleClick = () => { messenger.emit({ type: 'open_foo_dialog', data: "clicked inside the iframe will trigger the host to open a dialog"}); }">
import { TargetFrameMessenger as messenger, Message} from "cross-document-messenger";

export const Tabs: React.FC = () => {
  
useEffect(() => {
        messenger.subscribe((e: Message<any>) => {
        })
        return () => {
          messenger.unsubscribe();
        }
    }, [])
    
    .....
    
  const handleClick = () => {
        messenger.emit({ type: 'open_foo_dialog', data: "clicked inside the iframe will trigger the host to open a dialog"});
      }
You might also like...

ClientDB is an open source in-memory database for enabling real-time web apps.

ClientDB ClientDB is an open-source in-memory database for enabling real-time web apps. Build fast, scalable apps that feel silky smooth for users. In

Aug 27, 2022

Zero Two Bot,A fully Modular Whatsapp Bot to do everything possible in WhatsApp by Team Zero Two

Zero Two Bot,A fully Modular Whatsapp Bot to do everything possible in WhatsApp by Team Zero Two

🍭 𝗭𝗲𝗿𝗼 𝗧𝘄𝗼 𝗠𝗗 🍭 A Moduler WhatsApp Bot designed for both PM and Groups - To take your boring WhatsApp usage into a whole different level. T

Dec 25, 2022

Multiplies a number by zero. Useful for when you need to multiply a number by zero

multiply-by-zero Multiplies a number by zero. Useful for when you need to multiply a number by zero Please consider checking out the links of this pro

Jul 3, 2022

A beautiful, responsive, highly customizable and accessible replacement for JavaScript's popup boxes. Zero dependencies.Alerts ,dialogs

AsgarAlert (v1) for JS Install script defer src="/asgar-alert.js"/script Examples The most basic message: asgar("Hello world!"); A message signali

Dec 20, 2022

Stream Chat Messaging Example App

Stream Chat Messaging Example App Is your core product something that would benefit from the increased engagement that comes from in-app chat? With St

Nov 20, 2022

An Obsidian plugin that provides commands for bulk enabling/disabling of plugins and CSS Snippets

An Obsidian plugin that provides commands for bulk enabling/disabling of plugins and CSS Snippets

An Obsidian plugin that provides commands for bulk enabling/disabling of plugins and CSS Snippets. Useful for debugging when you have many plugins or CSS snippets.

Dec 27, 2022

Download Notion pages as markdown and image files, preserving hierarchy and enabling workflow properties. Works with Docusaurus.

Download Notion pages as markdown and image files, preserving hierarchy and enabling workflow properties. Works with Docusaurus.

notion-pull notion-pull lets you use Notion as your editor for markdown-based static site generators like Docusaurus. Using Notion instead of raw mark

Jan 7, 2023

A Gun DB extension that ships secure* ephemeral messaging between Gun peers using Bugout, secured by Gun's SEA suite

Bugoff A Gun DB extension that ships secure* ephemeral messaging between Gun peers using Bugout, secured by Gun's SEA suite About Bugoff creates an SE

Nov 12, 2022

A live instant messaging app that translates user messages into the other user's preferred language.

BabelFish Description BabelFish is an interactive multi-person chat app with built in live translation. It is created using the MERN stack (MongoDB, E

Jul 18, 2022
Owner
LironH
\m/ \m/ For those about to rock...
LironH
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A lightweight, performant, and simple-to-use wrapper component to stick section headers to the top when scrolling brings them to top

A lightweight, performant, and simple-to-use wrapper component to stick section headers to the top when scrolling brings them to top

Mayank 7 Jun 27, 2022
Zero dependencies, lightweight, and asynchronous https requests package.

This project is a Work in Progress and currently in development. The API is subject to change without warning. A small fetching package for super simp

Ray Arayilakath 11 Dec 8, 2022
This Photoshop script exports all top-level layers and groups to cropped PNG and JPEG files and creates a file usable in Tumult Hype 4 based on your Photoshop document.

Export To Hype (Photoshop Edition) This Photoshop script exports all top-level layers and groups to cropped PNG and JPEG files and creates a file usab

Max Ziebell 6 Nov 9, 2022
👌A useful zero-dependencies, less than 434 Bytes (gzipped), pure JavaScript & CSS solution for drop an annoying pop-ups confirming the submission of form in your web apps.

Throw out pop-ups confirming the submission of form! A useful zero-dependencies, less than 434 Bytes (gzipped), pure JavaScript & CSS solution for dro

Vic Shóstak 35 Aug 24, 2022
ClientDB is an open source in-memory database for enabling real-time web apps.

ClientDB ClientDB is an open source in-memory database for enabling real-time web apps. Build fast, scalable apps that feel silky smooth for users. In

Acapela 540 Dec 24, 2022
The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling rapid development of iofod extensions through the SDK.

iofod-sdk English | 简体中文 The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling

iofod, Inc. 47 Oct 17, 2022
Agetos is a web-platform messaging service founded in 2022. It has no purpose. Just like the other applications.

Start with a simple idea ?? Turn it into an awesome app ?? About Agetos is a web-platform messaging service founded in 2022. It has no purpose. Just l

flash 4 Aug 4, 2022