PostMessage RPC API Documentation - v0.2.2
    Preparing search index...

    Function providePlugin

    • Registers a plugin with the parent window using postMessage RPC communication.

      Call this function from within your plugin iframe to establish two-way communication with the parent window. This is the plugin-side counterpart to initFullscreenPlugin and initInlinePlugin.

      1. Plugin iframe loads and calls providePlugin()
      2. Plugin signals readiness via "domReady" message
      3. Parent sends "init" message with data, settings, and callback names
      4. Plugin receives initialization data and resolves the promise
      5. Plugin can now call parent hooks and handle parent method calls
      import { providePlugin } from '@micskeil/postmessage-rpc';

      // Register the plugin with the parent
      const { data, settings, hooks, terminate } = await providePlugin({
      // Callbacks from parent that this plugin can invoke
      hooks: ['onSave', 'onClose', 'onError'],

      // Methods that the parent can call
      methods: {
      getData: async () => {
      // Return plugin data to parent
      return { content: document.body.innerHTML };
      },

      setContent: async (content) => {
      // Update plugin from parent call
      document.body.innerHTML = content;
      return { success: true };
      },

      close: async () => {
      // Clean up when parent requests close
      terminate();
      return { success: true };
      }
      },

      // Validate initialization data
      validator: ({ data, settings }) => {
      if (!data.userId) {
      throw new Error('userId is required');
      }
      if (!settings.theme) {
      throw new Error('theme setting is required');
      }
      }
      });

      // Now you can use the parent-provided data and hooks
      console.log('Plugin initialized for user:', data.userId);
      console.log('Theme:', settings.theme);

      // Call parent hooks
      document.getElementById('save-btn').addEventListener('click', async () => {
      await hooks.onSave({ content: getEditorContent() });
      });

      document.getElementById('close-btn').addEventListener('click', async () => {
      await hooks.onClose();
      });
      const { data, settings, hooks } = await providePlugin({
      hooks: ['onSave', 'onClose'],
      methods: {
      // Get current note content
      getNote: async () => ({
      content: document.getElementById('editor').value,
      id: data.noteId
      }),

      // Set note content
      setNote: async (note) => {
      document.getElementById('editor').value = note.content;
      return { success: true };
      },

      // Apply theme
      setTheme: async (theme) => {
      document.body.className = `theme-${theme}`;
      return { success: true };
      }
      },
      validator: ({ data }) => {
      if (!data.noteId) throw new Error('noteId required');
      }
      });

      // Apply initial theme
      await hooks.onInit?.(settings.theme);

      // Wire up buttons
      document.getElementById('save').onclick = async () => {
      const note = await hooks.onSave({
      content: document.getElementById('editor').value
      });
      };

      The library automatically adds an "error" hook if not present. Use it to report errors:

      const { hooks } = await providePlugin({
      hooks: ['onError'], // Explicitly list if needed
      methods: {
      riskyOperation: async () => {
      try {
      return doSomethingRisky();
      } catch (error) {
      // Report error to parent
      await hooks.onError({
      message: error.message,
      code: 'RISKY_OP_FAILED'
      });
      return { success: false };
      }
      }
      }
      });

      Parameters

      • Optionaloptions: {
            hooks?: string[];
            methods?: Methods;
            validator?: (args: { data?: unknown; settings?: unknown }) => void;
        }

        Plugin configuration options

        • Optionalhooks?: string[]

          Array of parent callback names that this plugin accepts and can invoke

        • Optionalmethods?: Methods

          Map of method names to async functions the parent can call

        • Optionalvalidator?: (args: { data?: unknown; settings?: unknown }) => void

          Optional function to validate received data and settings from parent

      • currentWindow: Window = window

        The plugin's window object (defaults to window)

      • targetWindow: Window = window.parent

        The parent window object (defaults to window.parent)

      Returns Promise<ProvidedPlugin>

      Promise resolving to plugin interface containing:

      • data: Initial data sent by parent
      • settings: Configuration settings sent by parent
      • hooks: Functions to invoke parent callbacks
      • terminate: Function to cleanup and close communication

      If validator function throws or if initialization fails