δΈζ | Use Case | Update Log | Feedback bug | Gitee
Expand the table of contents
- Support directional communication and broadcast communication between different pages
- Supports pages that can be opened in any way, not limited to the window.open method
- Support communication between multiple sub-pages opened by the main page
- Support tagging and tracking the status of each page to facilitate global page management
- Support multiple method calls such as closing subpages
- Support monitoring page events
- Page survival check to ensure page status synchronization
- Support page to carry data and select sessionStorage as the storage source
- Typescript development, easy to use, small in size
npm i cross-window-message
import initMessager from 'cross-window-message';
<script src="https://cdn.jsdelivr.net/npm/cross-window-message/cross-window-message.min.js"></script>
<script>
console.log(initMessager);
</script>
The principle of cross-window-message
is based on window.onstorage event and localStorage for cross-page communication
Why not use window.open with postMessage and onMessage events? There are several reasons
- The conditions of use are relatively harsh, and only apply to pages opened with window.open
- Inconvenient communication between multiple sub-pages opened by the main page
- Cannot broadcast communication between multiple pages
- Unable to mark the status of each page
manual
When entering the page, call initMessager
to generate a Messager. This method supports passing in an optional parameter option, all of which are optional. The data structure is as follows:
interface IOptions {
pageName?: string;
pageId?: string;
data?: IJson;
useSessionStorage?: boolean;
}
- pageName represents the name of the page, and there can be the same page. If not passed in, use the pathname of the current page
- pageId represents the page ID, each new page must be unique. If not passed in, a default unique id will be generated
- The data carried on the current page will be written to storage
- Whether to use sessionStorage to store the state, the default is to use localStorage, this parameter needs to be consistent across all pages
import initMessager from 'cross-window-message';
const messager = initMessager({
pageName:'xxx'
});
After that, the communication between each page depends on this Messager.
Call initMessager
to generate a Messager, this method passes in optional option parameters
import initMessager from 'cross-window-message';
const messager = initMessager({
pageName:'xxx'
});
interface IOptions {
pageName?: string;
pageId?: string;
data?: IJson;
useSessionStorage?: boolean;
}
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;
onPageChange(fn: IOnPageChange): () => void;
onBeforeUnload(func: (event: BeforeUnloadEvent) => void): () => void;
onUnload(func: (event: Event) => void): () => void;
onClick(func: (event: MouseEvent) => void): () => void;
onShow(func: (event: Event) => void): () => void;
onHide(func: (event: Event) => void): () => void;
method: {
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 opened page
getLatestActivePage(): IPage | null; // Get the latest active page (the page that triggered the click or onshow event)
getAllPages(): IPage[]; // Get all open pages
updatePageData(data: IJson, cover?: boolean): boolean; // Update page data
}
}
interface IPage {
name: string; // the name of the page
id: string; // page id
index: number; // order of page opening
show: boolean; // Whether the page is visible
data?: IJson; // data carried on the page
}
interface IMsgData {
data: any; // data passed by postMessage
page: IPage; // Information on the source page
messageType: string | number; // messageType passed in by postMessage
messageId: string; // The unique message id generated
targetPageId?: string; // The targetPageId passed in when calling postMessageToTargetId can use this property to determine whether the message comes from the postMessageToTargetId method
targetPageName?: string; // The targetPageName passed in when calling postMessageToTargetName can use this property to determine whether the message comes from the postMessageToTargetName method
}
function postMessage(data: any, messageType?: number | string): void;
import initMessager from 'cross-window-message';
const messager = initMessager();
messager.postMessage({
text:'Hello World!'
})
Send data to all other pages (including yourself), the second parameter indicates the message type, can be empty
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, and other non-target pages will not receive the message
Other usage is consistent with postMessage
Listen to the message, this method will return a function, the execution can be used to cancel the monitoring
function onMessage(fn: (msgData: IMsgData) => void): () => void;
interface IMsgData {
data: any; // data passed by postMessage
page: IPage; // Information on the source page
messageType: string | number; // messageType passed in by postMessage
messageId: string; // The unique message id generated
targetPageId?: string; // The targetPageId passed in when calling postMessageToTargetId can use this property to determine whether the message comes from the postMessageToTargetId method
targetPageName?: string; // The targetPageName passed in when calling postMessageToTargetName can use this property to determine whether the message comes from the postMessageToTargetName method
}
interface IPage {
name: string; // the name of the page
id: string; // page id
index: number; // order of page opening
show: boolean; // Whether the page is visible
}
import initMessager from 'cross-window-message';
const messager = initMessager();
messager.onMessage((msgData)=>{
console.log(msgData);
})
Register for an event to receive messages
The parameter received by the event callback is an IMsgData type
Monitor all page change events, this method will return a function, the execution can be used to cancel the monitoring
function onPageChange(fn: (newQueue: IPage[], oldQueue: IPage[]) => void): () => void;
import initMessager from 'cross-window-message';
const messager = initMessager();
messager.onPageChange((newQueue, oldQueue)=>{
console.log(newQueue, oldQueue);
})
function onBeforeUnload(func: (event: BeforeUnloadEvent) => void): () => void;
function onUnload(func: (event: Event) => void): () => void;
function onClick(func: (event: MouseEvent) => void): () => void;
function onShow(func: (event: Event) => void): () => void;
function onHide(func: (event: Event) => void): () => void;
They are used to monitor the beforeunload, unload, click, visibilitychange event of the page respectively
The parameters are the same as the original
Some tool methods are exposed on the messager.method object
import initMessager from 'cross-window-message';
const messager = initMessager();
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 opened page
getLatestActivePage(): IPage | null; // Get the latest active page (the page that triggered the click or onshow event)
getAllPages(): IPage[]; // Get all open pages
updatePageData(data: IJson, cover?: boolean): boolean; // Update page data The cover parameter indicates whether the old data needs to be overwritten, the default is false
import initMessager from 'cross-window-message';
initMessager.version;