npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

magnethub-sdk

v0.1.1

Published

Two-way communication SDK for iframe-based WebGL games.

Readme

🧲 MagnetHub SDK

A lightweight, framework-agnostic JavaScript SDK for two-way communication between web platforms and embedded games (WebGL, Unity, Godot, Phaser, etc.) using iframes.

License npm version


✨ Features

  • 🚀 Lightweight — Pure JavaScript, no dependencies
  • 🔄 Two-way Communication — Parent ↔ Iframe messaging using postMessage
  • 🎮 Game Engine Ready — Easy integration with Unity, Godot, Phaser, and more
  • 📦 Framework Agnostic — Works with any web framework or vanilla JS
  • 🛡️ Type Safe — Includes TypeScript definitions (optional)
  • 📖 Well Documented — Complete API docs and examples

📦 Installation

Using npm

# Latest version
npm install @magnethub-sdk

# Specific version
npm install @[email protected]

Using CDN (unpkg)

<!-- Latest version -->
<script type="module">
  import MagnetHubCore from 'https://unpkg.com/@magnethub/sdk/src/magnethub-core.js';
</script>

<!-- Specific version (recommended for production) -->
<script type="module">
  import MagnetHubCore from 'https://unpkg.com/@magnethub/[email protected]/src/magnethub-core.js';
</script>

Using CDN (jsDelivr)

<!-- Specific version -->
<script type="module">
  import MagnetHubCore from 'https://cdn.jsdelivr.net/npm/@magnethub/[email protected]/src/magnethub-core.js';
</script>

Direct Download

Clone or download from GitHub:

# Clone latest
git clone https://github.com/magnet-hub/magnethub-sdk.git

# Clone specific version
git clone --branch v0.1.0 https://github.com/magnet-hub/magnethub-sdk.git

Check SDK Version

import MagnetHubCore from '@magnethub/sdk';
console.log(MagnetHubCore.VERSION); // "0.1.0"

🚀 Quick Start

Parent Page (Host Site)

<!DOCTYPE html>
<html>
  <head>
    <title>Game Platform</title>
  </head>
  <body>
    <iframe id="gameFrame" src="game.html" width="800" height="600"></iframe>

    <script type="module">
      import MagnetHubCore from './src/magnethub-core.js';

      const hub = new MagnetHubCore({
        iframeId: 'gameFrame',
        apiKey: 'your-api-key',
      });

      // Listen for events from the game
      hub.on('score', (data) => {
        console.log('Score:', data.score);
      });

      hub.on('gameOver', (data) => {
        console.log('Game Over! Final Score:', data.score);
      });

      // Send events to the game
      hub.send('startGame', { level: 1 });
    </script>
  </body>
</html>

Game Page (Embedded Iframe)

<!DOCTYPE html>
<html>
  <head>
    <title>My Game</title>
  </head>
  <body>
    <canvas id="gameCanvas"></canvas>

    <script type="module">
      import MagnetHubGame from './src/magnethub-game.js';

      const hub = new MagnetHubGame();

      // Notify parent that game is loaded
      hub.send('gameLoaded');

      // Listen for events from parent
      hub.on('startGame', (data) => {
        console.log('Starting game at level:', data.level);
        // Start game logic here
      });

      hub.on('pauseGame', () => {
        // Pause game logic
      });

      // Send score updates
      function updateScore(score) {
        hub.send('score', { score });
      }

      // Send game over event
      function endGame(finalScore) {
        hub.send('gameOver', { score: finalScore });
      }
    </script>
  </body>
</html>

📖 API Reference

MagnetHubCore (Parent Page)

Constructor

new MagnetHubCore({ iframeId, apiKey });

Parameters:

  • iframeId (string, required) - ID of the iframe element
  • apiKey (string, optional) - API key for authentication

Methods

.send(event, data)

Sends a message to the game iframe.

hub.send('pauseGame', { reason: 'User paused' });

.on(event, callback)

Listens for events from the game iframe.

hub.on('score', (data) => {
  console.log('Score:', data.score);
});

MagnetHubGame (Game Iframe)

Constructor

new MagnetHubGame();

Methods

.send(event, data)

Sends a message to the parent page.

hub.send('score', { score: 1000 });

.on(event, callback)

Listens for events from the parent page.

hub.on('pauseGame', () => {
  // Pause game
});

🎮 Game Engine Integration

Unity WebGL

Create a C# script to bridge Unity with MagnetHub:

using UnityEngine;
using System.Runtime.InteropServices;

public class MagnetHubBridge : MonoBehaviour
{
    [DllImport("__Internal")]
    private static extern void SendToParent(string eventName, string jsonData);

    void Start()
    {
        SendToParent("gameLoaded", "{}");
    }

    public void SendScore(int score)
    {
        string json = $"{{\"score\": {score}}}";
        SendToParent("score", json);
    }
}

Create Assets/Plugins/WebGL/MagnetHubPlugin.jslib:

mergeInto(LibraryManager.library, {
  SendToParent: function (eventName, jsonData) {
    var event = UTF8ToString(eventName);
    var data = JSON.parse(UTF8ToString(jsonData));

    window.parent.postMessage(
      {
        event: event,
        data: data,
        source: 'magnethub-game',
      },
      '*'
    );
  },
});

Godot Web Export

extends Node

func send_to_parent(event_name: String, data: Dictionary):
    if OS.has_feature("JavaScript"):
        var json_data = JSON.print(data)
        var js_code = """
        window.parent.postMessage({
            event: '%s',
            data: %s,
            source: 'magnethub-game'
        }, '*');
        """ % [event_name, json_data]

        JavaScript.eval(js_code)

func _ready():
    send_to_parent("gameLoaded", {})

func send_score(score: int):
    send_to_parent("score", {"score": score})

Phaser.js

import MagnetHubGame from './src/magnethub-game.js';

const hub = new MagnetHubGame();

const config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  scene: {
    create: function () {
      hub.send('gameLoaded');

      hub.on('pauseGame', () => {
        this.scene.pause();
      });
    },
  },
};

const game = new Phaser.Game(config);

📚 Documentation


🧪 Testing Locally

  1. Clone the repository:

    git clone https://github.com/magnet-hub/magnethub-sdk.git
    cd magnethub-sdk
  2. Serve the examples:

    npx serve examples
  3. Open your browser:

    http://localhost:3000/parent.html

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

# Fork and clone the repo
git clone https://github.com/YOUR-USERNAME/magnethub-sdk.git
cd magnethub-sdk

# Install dependencies
npm install

# Test examples
npx serve examples

📋 Common Events

Parent → Game

| Event | Description | Example Data | | ------------ | --------------- | --------------------------- | | startGame | Start the game | { level: 1 } | | pauseGame | Pause the game | { reason: 'User paused' } | | resumeGame | Resume the game | null | | resetGame | Reset the game | null |

Game → Parent

| Event | Description | Example Data | | --------------- | --------------------- | --------------------------- | | gameLoaded | Game finished loading | { timestamp: 1234567890 } | | score | Score update | { score: 1000 } | | gameOver | Game ended | { score: 1500 } | | levelComplete | Level completed | { level: 1, score: 500 } |


🛡️ Security

  • Always validate incoming data
  • Use specific origins in production instead of '*'
  • Don't send sensitive data through postMessage

📄 License

This project is licensed under the Apache 2.0 License - see the LICENSE file for details.

Copyright 2025 MagnetHub

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

🙏 Acknowledgments

Built with ❤️ by the MagnetHub team.


📞 Support


Made with 🧲 by MagnetHub