Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@opensea/vessel

Package Overview
Dependencies
Maintainers
0
Versions
494
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@opensea/vessel

Promise based wrapper for postMessage API 🚢

  • 0.7.116
  • npm
  • Socket score

Version published
Weekly downloads
2.6K
increased by58.6%
Maintainers
0
Weekly downloads
 
Created
Source

OpenSea Vessel 🚢

A promise based wrapper for the postMessage API for communications between a parent app and an iframed child app.

OpenSea Vessel can be used to send messages between a parent app and an iframed app, and await responses to messages. Example: Confirmation of receipt, result of RPC call.

Installation

You guessed it!

pnpm install @opensea/vessel

Getting Started

Import the Vessel class

import { Vessel } from "@opensea/vessel"

Vessel class contains logic for sending and receiving messages via the postMessage. It can be used in both the parent app and child app.

Parent app

The parent app mounts the iframe that loads the child app. The parent app must pass a reference to the child iframe element into the Vessel class constructor. It is used to access the postMessage method of the iframe window.

// NOTE: Replace with reference to your iframe
const iframe = document.createElement("iframe")
const vessel = new Vessel({ iframe })

Child app

The child app is mounted in an iframe and has access to the postMessage API of its parent app's window by default. It does not require any extra params to be initialized.

const vessel = new Vessel()

Vessel Constructor

Vessel instances can be constructed with an options object. It includes the following properties:

PropertyDescriptionDefault
iframeThe iframe element to communicate with. If not provided the constructed instance will be a child vessel.undefined (instance is child vessel)
applicationThe application name to use for vessel messages. Must be shared between parent and child."opensea-vessel"
defaultTimeoutDefault number of milliseconds to wait for a message response before throwing a TimeoutError5_000 (5s)
handshakeTimeoutNumber of milliseconds to wait for a handshake response before throwing a HandshakeTimeoutError10_000 (10s)
targetOriginThe target origin for the iframe or parent window to connect to. Directly used as postMessage targetOrigin."*" (Any origin)
debugWhether to log debug messages to the console.false

Sending messages

Sending messages from parent and child via a Vessel class instance is the same.

// Examples
const response = await vessel.send("Any payload!")
const objectPayload = await vessel.send({
  foo: "bar",
  baz: { odee: ["nested", "is", "fine"] },
})
const customTimeout = await vessel.send(
  "If no response in 3 seconds this promise will reject.",
  { timeout: 3_000 },
)
const noTimeout = await vessel.send("This promise might never resolve.", {
  timeout: undefined,
})

The send method takes any JSON serializable payload as first param and an options object as the second. The options object includes the following properties:

PropertyDescriptionDefault
timeoutNumber of milliseconds to wait for a response before throwing a TimeoutError5_000 (5s)

Handling incoming messages

The Vessel class can be used to add message listeners and exposes a convenient reply function for listeners to use. Message listener must return a boolean to indicate whether they handled the message or not.

type VesselMessageListener = (
  message: VesselMessage,
  reply: (response: unknown, options: ReplyOptions) => void,
) => boolean

// Example listener
vessel.addMessageListener((message, reply) => {
  if (message.shouldBeHandledHere) {
    const result = handleThisMessage(message)
    reply(result)
    return true
  } else {
    return false
  }
})

Replying with errors

Sometimes the response to a message is an error and it is preferrable for the send method to throw an error for the sender to handle. Replying to a message with the options error boolean set to true will cause sender to reject the send promise with the payload as an error when teh response is received.

interface ReplyOptions {
  error?: boolean
}

// Example reply error
vessel.addMessageListener((message, reply) => {
  if (message.shouldBeHandledHere) {
    try {
      const result = handleThisMessage(message)
      reply(result)
    } catch (error) {
      reply(
        { reason: "Handling failed", stepsToFix: [1, 2, 3] },
        { error: true },
      )
    }
    return true
  } else {
    return false
  }
})

FAQs

Package last updated on 24 Dec 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc