Skip to content

Commit

Permalink
chore: add webkit channel
Browse files Browse the repository at this point in the history
  • Loading branch information
Jack-Works committed Aug 8, 2022
1 parent 7269268 commit b472513
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/strong-cherries-kneel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@dimensiondev/webextension-polyfill': patch
---

add WebkitChannel
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
},
"dependencies": {
"@masknet/compartment": "^0.2.3",
"@masknet/intrinsic-snapshot": "^0.1.0"
"@masknet/intrinsic-snapshot": "^0.1.0",
"async-call-rpc": "^6.1.1"
},
"publishConfig": {
"registry": "https://npm.pkg.github.com"
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions src/core/rpc/channel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/// <reference path="../../types/globals.d.ts" />
import type { EventBasedChannel } from 'async-call-rpc'
import { isDebugMode } from '../debugger/enabled.js'

const key = 'holoflowsjsonrpc'
export class WebkitChannel implements EventBasedChannel {
constructor() {
document.addEventListener(key, (e) => {
const detail = (e as CustomEvent<any>).detail
for (const f of this.listener) {
try {
f(detail)
} catch {}
}
})
}
private listener: Set<(data: unknown) => void> = new Set()
on(cb: (data: any) => void) {
this.listener.add(cb)
return () => this.listener.delete(cb)
}
send(data: any): void {
if (isDebugMode) {
console.log('send', data)
}
const handler = window.webkit?.messageHandlers?.[key]
if (handler) handler.postMessage(data)
}
}
7 changes: 7 additions & 0 deletions src/types/globals.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
declare var webkit: undefined | WebkitAPI
interface WebkitAPI {
messageHandlers?: Record<string, WebkitMessageHandler>
}
interface WebkitMessageHandler {
postMessage(data: unknown): void
}

0 comments on commit b472513

Please sign in to comment.