Skip to content

Function: createJsonEndpoint()

createJsonEndpoint(stringEndpoint, name): PostMessageEndpointBase<any>

Converts a PostMessageEndpointString to a PostMessageEndpoint by using JSON serialization/deserialization

Parameters

stringEndpoint

PostMessageEndpointBase<string>

The string-based endpoint to convert

name

string = ''

Returns

PostMessageEndpointBase<any>

A PostMessageEndpoint that accepts any data and converts it to/from JSON strings

@NO_SIDE_EFFECTS

Example

typescript
const stringEndpoint: PostMessageEndpointString = getStringEndpoint()
const jsonEndpoint = createJsonEndpoint(stringEndpoint)

// Send any data - it will be JSON.stringify'd automatically
jsonEndpoint.postMessage({ hello: 'world', count: 42 })

// Receive parsed objects automatically
jsonEndpoint.addEventListener('message', (event) => {
  console.log(event.data) // Already parsed: { hello: 'world', count: 42 }
})

Released under the MIT License.