Last active
July 29, 2022 12:01
-
-
Save WebReflection/7ab0addec037508cc8380a9c37d285f2 to your computer and use it in GitHub Desktop.
A GJS WebKit JSON Communication Channel Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const JSONChannel = (Private => class JSONChannel { | |
// (c) Andrea Giammarchi - @WebReflection (ISC) | |
constructor(secret=Array.from( | |
crypto.getRandomValues(new Uint8Array(8)) | |
).map(i => i.toString(36)).join('')) { | |
const listener = e => this.emit('message', null, e.detail); | |
document.addEventListener(`${secret}:gjs`, listener); | |
Private.set(this, { | |
secret, listener, | |
fn: Object.create(null) | |
}); | |
} | |
close() { | |
const ref = Private.get(this); | |
Private.delete(this); | |
document.removeEventListener(`${ref.secret}:gjs`, ref.listener); | |
} | |
send(data) { | |
document.title = `${Private.get(this).secret}:js=${JSON.stringify(data)}`; | |
// one day the following should work instead | |
// webkit.messageHandlers[Private.get(this).secret].postMessage(data); | |
} | |
emit(type, err, data) { | |
const listeners = Private.get(this); | |
if (type in listeners) listeners[type].forEach( | |
fn => fn.call(this, err, data) | |
); | |
} | |
on(type, fn) { | |
const listeners = Private.get(this); | |
if (!(type in listeners)) listeners[type] = new Set; | |
listeners[type].add(fn); | |
return this; | |
} | |
removeListener(type, fn) { | |
const listeners = Private.get(this); | |
if (type in listeners) listeners[type].delete(fn); | |
return this; | |
} | |
})(new WeakMap); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternative full GJS program
Alternative page code