Elegant cross window communication and global page management solution cross window message js library for sending messages from different windows

Posted by optikalefx on Wed, 09 Feb 2022 23:30:10 +0100

🚀 Elegant cross window communication and global page management solution cross-window-message

Share a cross window communication and global page management developed by myself

0. Characteristics

  1. Support directional communication and broadcast communication between different pages
  2. It supports pages opened in any way, not limited to window Open method
  3. Support communication between multiple sub pages opened by the main page
  4. It supports marking and tracking the status of each page to facilitate global page management
  5. Support multiple method calls such as closing sub pages
  6. Support listening for page events

1. Installation and use

1.1 npm

npm i cross-window-message
import initMessager from 'cross-window-message'; 

1.2 cdn introduction

<script src="https://cdn.jsdelivr.net/npm/cross-window-message/cross-window-message.min.js"></script>
<script>
    console.log(initMessager);
</script>

2. Introduction to use

The principle of cross window message is based on window OnStorage event and localStorage for cross page communication

Why not use window There are several reasons why open matches the postMessage and onMessage events

  1. The use conditions are harsh, which is only applicable to the use of window Open open page
  2. It is inconvenient to communicate between multiple sub pages opened by the main page
  3. Cannot broadcast communication between multiple pages
  4. Unable to mark individual page status

Use process

When entering the page, call initMessager to generate a Messager. This method supports passing in two optional parameters, pageName and pageId

pageName refers to the page name, which can have the same page. If not, the pathname of the current page is used

pageId represents the page ID, and each new page must be unique. If not, a default unique ID will be generated

import initMessager from 'cross-window-message'; 
const messager = initMessager('pageName', 'pageId');

After that, the communication between various pages depends on this Messager

3. api

3.1 Messager ts declaration

interface IMessager {
    pageId: string;
    pageName: string;
    postMessage(data: any, messageType?: number | string): void;
    postMessageToTargetId(targetPageId: string, data: any, messageType?: number | string): void;
    postMessageToTargetName(targetPageName: string, data: any, messageType?: number | string): void;
    onMessage(fn: (msgData: IMsgData) => void): () => void;
    onUnload(func: (event: BeforeUnloadEvent) => void): () => void;
    onClick(func: (event: MouseEvent) => void): () => void;
    onShow(func: (event: Event) => void): () => void;
    onHide(func: (event: Event) => void): () => void;
    method: {
        closeOtherPage(): void;
        closeOtherSamePage(): void;
        alertInTargetName(text: string | number, pageName: string): void;
        alertInTargetId(text: string | number, pageId: string): void;
        closePageByPageName(pageName: string): void;
        closePageByPageId(pageId: string): void;
        getLastOpenPage(): IPage | null;
        getLatestActivePage(): IPage | null;
        getAllPages(): IPage[];
    }
}

interface IPage {
    name: string;
    id: string;
    index: number;
    show: boolean;
}
interface IMsgData {
    data: any;
    page: IPage;
    messageType: string | number;
    messageId: string;
    targetPageId?: string;
    targetPageName?: string;
}

3.2 pageId and pageName

Incoming or generated page id and page name properties

3.3 postMessage method

function postMessage(data: any, messageType?: number | string): void;
import initMessager from 'cross-window-message'; 
const messager = initMessager('pageName', 'pageId');
messager.postMessage({
    text: 'Hello World!'
})

Send data to all other pages (including yourself). The second parameter represents the message type and can be blank

3.4 postMessageToTargetId and postMessageToTargetName

function postMessageToTargetId(targetPageId: string, data: any, messageType?: number | string): void;
function postMessageToTargetName(targetPageName: string, data: any, messageType?: number | string): void;

These two methods are used to send data to the page with the specified pageId or pageName. Other non target pages will not receive messages

Other usage is consistent with that of postMessage

3.5 onMessage

function onMessage(fn: (msgData: IMsgData) => void): () => void;

interface IMsgData {
    data: any; // data passed in by postMessage
    page: IPage; // Information on the message source page
    messageType: string | number; // messageType passed in by postMessage
    messageId: string; // Unique message id generated
    targetPageId?: string; // The targetPageId passed in when calling postMessageToTargetId can be used to determine whether the message comes from the method of postMessageToTargetId
    targetPageName?: string;  // The targetPageName passed in when calling postMessageToTargetName can be used to determine whether the message comes from the method of postMessageToTargetName
}
interface IPage {
    name: string; // The name of the page
    id: string; // Page id
    index: number; // Order of page opening
    show: boolean; // Is the page visible
}
import initMessager from 'cross-window-message'; 
const messager = initMessager('pageName', 'pageId');
messager.onMessage((msgData)=>{
    console.log(msgData);
})

Register an event to receive messages

The parameter received by the event callback is an IMsgData type

3.6 page events

function onUnload(func: (event: BeforeUnloadEvent) => void): () => void;
function onClick(func: (event: MouseEvent) => void): () => void;
function onShow(func: (event: Event) => void): () => void;
function onHide(func: (event: Event) => void): () => void;

It is used to listen to the beforeunload click visibilitychange event of the page

Parameters are consistent with native

3.7 tools and methods

messager. Some tool methods are exposed on the method object

import initMessager from 'cross-window-message'; 
const messager = initMessager('pageName', 'pageId');
messager.method.closeOtherPage()
closeOtherPage(): void; // Close all other pages
closeOtherSamePage(): void; // Close all other pages with the same pageName as the current page
alertInTargetName(text: string | number, pageName: string): void; // alert a message on the target pageName page
alertInTargetId(text: string | number, pageId: string): void; // alert a message on the target pageId page
closePageByPageName(pageName: string): void; // Close all target pageName pages
closePageByPageId(pageId: string): void; // Close the target pageId page
getLastOpenPage(): IPage | null; // Get the latest open page
getLatestActivePage(): IPage | null; // Get the latest active page on click event
getAllPages(): IPage[]; // Get all open pages

Version 3.8

import initMessager from 'cross-window-message'; 
initMessager.version;

Topics: TypeScript