UNPKG

znapi

Version:

Better TS/JS API for zeronet-conservancy (WIP)

64 lines (63 loc) 1.9 kB
import { ZNAPIGeneric } from './common.js'; export class WWAPI extends ZNAPIGeneric { waitingCb; wrapperNonce; nextMessageId; target; constructor(config) { super(); this.waitingCb = {}; this.wrapperNonce = document.location.href.replace(/.*wrapper_nonce=([A-Za-z0-9]+).*/, "$1"); this.nextMessageId = 1; } connect() { this.target = window.parent; window.addEventListener('message', e => this.onMessage(e), false); this.cmd('innerReady'); } cmd(cmd, params = {}, cb = null) { this.send({ cmd: cmd, params: params }, cb); } send(message, cb = null) { message.wrapper_nonce = this.wrapperNonce; message.id = this.nextMessageId; ++this.nextMessageId; this.target.postMessage(message, '*'); if (cb) { this.waitingCb[message.id] = cb; } } onMessage(e) { const message = e.data; const cmd = message.cmd; if (cmd === 'response') { if (this.waitingCb[message.to] !== undefined) { this.waitingCb[message.to](message.result); delete this.waitingCb[message.to]; } else { console.log("Websocket callback not found:", message); } } else if (cmd === 'wrapperReady') { this.cmd('innerReady'); } else if (cmd === 'ping') { console.log('ping'); // this.response(message.id, 'pong'); } else if (cmd === 'wrapperOpenedWebsocket') { // this.onOpenWebsocket() } else if (cmd === 'wrapperClosedWebsocket') { // this.onCloseWebsocket() } else { this.processCallback(cmd, message); // this.onRequest(cmd, message) } } }