post-message.ts

48 lines | 1.619 kB Blame History Raw Download
import { messageListener } from "./message-listener";

export function postMessage(window: Window | null | undefined, type: string, value: any, onResponse?: (executeTimeInMs: number, exceedTimeInMs: number) => void): Function {
    var postId = +new Date();
    var responseTimeout = 5000;
    var execResponse = true;

    if (window && type && value) {
        if (onResponse) {
            var timeoutHandle: number | null = null;

            var remListener = messageListener((type, value, id) => {
                if (type == "response" && id == postId) {
                    if (timeoutHandle != null)
                        clearTimeout(timeoutHandle);

                    remListener();
                    if (execResponse)
                        onResponse(+new Date() - id, responseTimeout);
                }
            });

            timeoutHandle = setTimeout(() => {
                remListener();
                if (timeoutHandle != null) {
                    clearTimeout(timeoutHandle);
                    if (execResponse)
                        onResponse(-1, responseTimeout);
                }
            }, responseTimeout);
        }

        window.postMessage({ type: type, value: (typeof value === 'string' || value instanceof String) ? value : JSON.stringify(value), id: postId }, "*");
    }

    return () => {
        if (onResponse) {
            execResponse = false;
        }
    };

}

export function postResponseMessage(window: Window | null | undefined, id: number, value: any) {
    if (window && value) {
        window.postMessage({ type: "response", value: JSON.stringify(value), id: id }, "*");
    }
}