{"_id":"@2k/post-message","_rev":"17-2a9bd9a249ec0d4bd5fb7e492514a25f","name":"@2k/post-message","dist-tags":{"latest":"0.0.11"},"versions":{"0.0.10":{"name":"@2k/post-message","version":"0.0.10","keywords":["promise","post-message","postMessage","sendMessage","onMessage"],"author":{"name":"scriptpower"},"license":"MIT","_id":"@2k/post-message@0.0.10","maintainers":[{"name":"scriptpower","email":"scriptpower@qq.com"}],"dist":{"shasum":"a6ba3228847f5a4e84d0520be099c8bec6df7b76","tarball":"https://registry.npmjs.org/@2k/post-message/-/post-message-0.0.10.tgz","fileCount":6,"integrity":"sha512-mymTYSIrtxxpz53QtFwFYqwRANqrtlM7RJtPIRQR8GuHJY8hp0TLw9JMh3mmkWIQNgfV2XEXXfn57f+wDaVUVQ==","signatures":[{"sig":"MEUCIDv0vrMX3j3b0xXcxjWhqe4yeGPOSFapZTKyeAXlTojmAiEA/DWApPB8XdpzgHB1coLgq1Aw/J2HHGCcmcIVw3Dh+Fs=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":11681},"main":"index.cjs","type":"module","types":"index.d.ts","unpkg":"index.iife.js","module":"index.js","exports":{"types":"./index.d.ts","import":"./index.js","default":"./index.js","require":"./index.cjs"},"gitHead":"191f3221d9f3b6bc787c7cc45900603cb4cf6cc0","scripts":{},"_npmUser":{"name":"scriptpower","email":"scriptpower@qq.com"},"jsdelivr":"index.iife.js","_npmVersion":"10.8.3","description":"Simple promise based post message / listener","directories":{},"_nodeVersion":"20.12.2","dependencies":{},"publishConfig":{"access":"public","registry":"https://registry.npmjs.com/"},"_hasShrinkwrap":false,"_npmOperationalInternal":{"tmp":"tmp/post-message_0.0.10_1729309014310_0.27706035531213513","host":"s3://npm-registry-packages"}},"0.0.11":{"name":"@2k/post-message","version":"0.0.11","description":"Simple promise based post message / listener","keywords":["promise","post-message","postMessage","sendMessage","onMessage"],"type":"module","main":"index.cjs","module":"index.js","types":"index.d.ts","unpkg":"index.iife.js","jsdelivr":"index.iife.js","exports":{"default":"./index.js","import":"./index.js","require":"./index.cjs","types":"./index.d.ts"},"scripts":{},"dependencies":{},"publishConfig":{"registry":"https://registry.npmjs.com/","access":"public"},"author":{"name":"scriptpower"},"license":"MIT","_id":"@2k/post-message@0.0.11","gitHead":"51c667a2181a864086c2daabd1a337b05dbc1486","_nodeVersion":"20.12.2","_npmVersion":"10.8.3","dist":{"integrity":"sha512-J6b0KVC+RIAgyhSfxBrzKav9Bd/GtxvhpcJaKtTm6zK6lzXI+fVdAaO7iNtoZVcHkacmWuD+nu8G5I5qFVxg8w==","shasum":"fc4fa89b728c3dc0a63167f86a39807244632518","tarball":"https://registry.npmjs.org/@2k/post-message/-/post-message-0.0.11.tgz","fileCount":6,"unpackedSize":13263,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFvEdxbZBCbNfu7+gCTvaxygWoT0MPU5WaWSB5hXfU4qAiA27leOsAAo6Q1358MTqjGXeiWqyjMkO7agyj7lJ+ywxA=="}]},"_npmUser":{"name":"scriptpower","email":"scriptpower@qq.com"},"directories":{},"maintainers":[{"name":"scriptpower","email":"scriptpower@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/post-message_0.0.11_1729340877831_0.7306828179434437"},"_hasShrinkwrap":false}},"time":{"created":"2024-10-18T06:47:23.226Z","modified":"2024-10-19T12:27:58.234Z","0.0.2":"2024-10-18T06:47:23.589Z","0.0.3":"2024-10-18T23:41:39.560Z","0.0.4":"2024-10-19T00:11:12.956Z","0.0.5":"2024-10-19T00:32:41.391Z","0.0.6":"2024-10-19T00:52:08.585Z","0.0.7":"2024-10-19T01:06:12.088Z","0.0.8":"2024-10-19T01:10:39.599Z","0.0.9":"2024-10-19T03:13:49.428Z","0.0.10":"2024-10-19T03:36:54.534Z","0.0.11":"2024-10-19T12:27:58.043Z"},"author":{"name":"scriptpower"},"license":"MIT","keywords":["promise","post-message","postMessage","sendMessage","onMessage"],"description":"Simple promise based post message / listener","maintainers":[{"name":"scriptpower","email":"scriptpower@qq.com"}],"readme":"# @2k/post-message\n\nSimple promise based post message / listener.\n\n## Usage\n\n### (1) onMessage\n```js\nimport { onMessage } from '@2k/post-message';\n\nconst cb = async (msg) => {\n    console.log(msg.oid, msg.origin, msg.data)\n    // wait some async operation\n    const resp = await foo(msg.data);\n    return resp;\n}\n\n// source: all\nconst unSub_all = onMessage(cb);\nconst unSub_star = onMessage('*', cb);\n\n// source: window\nconst unSub_1 = onMessage(\n    window.parent,\n    cb\n);\n\n// source: iframe\nconst unSub_2 = onMessage(\n    document.getElementById('iframe'),\n    cb // callback\n);\n\n// source: iframe.contentWindow\nconst unSub_3 = onMessage(\n    document.getElementById('iframe').contentWindow,\n    cb\n);\n```\n\n### (2) sendMessage\n```js\nimport { sendMessage } from '@2k/post-message';\n\n// target: window\nconst resp_1 = await sendMessage(\n    window.parent,\n    { name: 'foo' },\n    {\n        needResponse: true,\n        timeout: 10000 // response timeout\n    }\n);\nconsole.log(resp_1.result)\n\n// target: iframe\nconst resp_2 = await sendMessage(\n    document.getElementById('iframe')\n    { name: 'bar' },\n);\nconsole.log(resp_2.result)\n\n// target: iframe.contentWindow\nconst resp_3 = await sendMessage(\n    document.getElementById('iframe').contentWindow\n    { name: 'baz' },\n);\nconsole.log(resp_3.result)\n```\n\n### (3) Create a simple forwarding bridge\n\n```html\n<!-- bridge.html--->\n<script src=\"https://unpkg.com/@2k/post-message\"></script>\n<iframe id=\"iframeA\" src=\"https://a.com/a.tml\"></iframe>\n<iframe id=\"iframeB\" src=\"https://b.com/b.html\"></iframe>\n<script>\nconst {onMessage, sendMessage} = twoK\nconst iframeA = document.getElementById(\"iframeA\");\nconst iframeB = document.getElementById(\"iframeB\");\nonMessage(iframeA, (msg) => sendMessage(iframeB, msg.data));\nonMessage(iframeB, (msg) => sendMessage(iframeA, msg.data));\n</script>\n\n<!-- https://a.com/a.tml--->\n<input id=\"input\" type=\"text\" value=\"a\" onkeyup=\"send()\">\n<script>\nconst {onMessage, sendMessage} = twoK\nonMessage(parent, async (msg) => {\n    document.getElementById('input').value = msg.data\n    return `A received : ${msg.data}`\n})\nasync function send() {\n    const value = document.getElementById('input').value\n    const [err, res] = await sendMessage(parent, value, {\n        needResponse: true,\n        timeout: 1000\n    }).then(res => [null, res], (err) => [err])\n    console.log(['A send done', err, res?.result])\n}\n</script>\n\n<!-- https://b.com/b.html--->\n<input id=\"input\" type=\"text\" value=\"b\" onkeyup=\"send()\">\n<script>\nconst {onMessage, sendMessage} = twoK\nonMessage(parent, async (msg) => {\n    document.getElementById('input').value = msg.data\n    return `B received : ${msg.data}`\n})\nasync function send() {\n    const value = document.getElementById('input').value\n    const [err, res] = await sendMessage(parent, value, {\n        needResponse: true,\n        timeout: 1000\n    }).then(res => [null, res], (err) => [err])\n    console.log(['B send done', err, res?.result])\n}\n</script>\n```\n\n## Types\n\n```ts\ntype Endpoint = 'parent' | 'child';\ntype SendOptions = {\n    origin?: string;\n    endpoint?: Endpoint;\n    needsResponse?: boolean;\n    timeout?: number;\n};\ntype MsgBody<T> = {\n    oid: number;\n    data: T;\n    ctime: number;\n    origin?: string;\n};\ntype MsgResp<T> = {\n    oid: number;\n    result: T;\n    ctime: number;\n};\ntype MsgCb<T, R> = (msg: MsgBody<T>) => Promise<R> | R;\n\n/**\n * Listen to messages from a source frame.\n *\n * @param { function } cb - optional source frame, listens to all messages if not provided.\n * @returns { function } - unsubscribe function\n */\ndeclare function onMessage<T, R>(cb: MsgCb<T, R>): () => boolean;\n\n/**\n * Listen to messages from a source frame.\n *\n * @param { HTMLIFrameElement | Window | '*' | function } source - optional source frame, listens to all messages if not provided.\n * @param { function } cb - callback function\n * @returns { function } - unsubscribe function\n */\ndeclare function onMessage<T, R>(\n    source: HTMLIFrameElement | Window | '*',\n    cb: MsgCb<T, R>): () => boolean;\n\n/**\n * Listen to messages from a source DOM Node.\n *\n * @param { HTMLElement } source - optional source frame, listens to all messages if not provided.\n * @param { function } cb\n * @param { \"parent\" | \"child\" } endpoint\n * @returns { function } - unsubscribe function\n */\ndeclare function onMessage<T, R>(\n    source: HTMLElement,\n    cb: MsgCb<T, R>,\n    endpoint: Endpoint): () => boolean;\n\n/**\n * Send messages to a target frame or DOM node.\n *\n * @param { HTMLIFrameElement | HTMLElement | Window } target - The target window | iframe | DOM node\n * @param { * } data - The message payload\n * @param { SendOptions } options - The options\n * @returns { Promise<Response> } - Response\n */\ndeclare function sendMessage<T, R>(\n    target: HTMLIFrameElement | HTMLElement | Window,\n    data: T,\n    options?: SendOptions): Promise<MsgResp<Awaited<R>>>;\n```\n","readmeFilename":"readme.md"}