Search by

bossartemii / matframe

bossartemii

PHP helpers for MatFrame, an <iframe> wrapper web component: auto-height, Promise messaging, fallback.

Package info

github.com/bossartemii/matframe

Language:JavaScript

pkg:composer/bossartemii/matframe

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 2

Open Issues: 0

v0.1.3 2026-12-02 02:36 UTC

This package is auto-updated.

Last update: 2026-12-02 02:45:17 UTC


README

An <iframe> wrapper for embeds you control. One tag, <mat-frame>, that sizes itself to its content, talks to the page with cancellable Promises, and never fails silently.

npm CI size ยท Zero dependencies ยท ~4.5 KB gzipped ยท works with React, Vue, Angular, PHP, Svelte or plain HTML.

๐Ÿ‡ฎ๐Ÿ‡น Leggi in italiano ยท โ–ถ๏ธ Live demo

<script src="https://cdn.jsdelivr.net/npm/matframe@0.1/matframe.min.js"></script>

<mat-frame src="https://widget.example.com" auto-height lazy handshake></mat-frame>

When to use it (and when not)

Use MatFrame for embeds where you control or integrate with both sides: widgets, previews, dashboards, checkout or chat panels. That's where you keep rewriting height syncing, postMessage glue and a fallback state.

For static embedding (documentation frames, a third-party page you just display) a plain <iframe> is simpler and the right tool.

Why

<iframe> <mat-frame>
Height Fixed: scrollbars or empty space Follows the content, even cross-origin
Communication Raw postMessage, no replies call() with Promises both ways, events, timeouts, AbortSignal
Errors and blocks Blank box, no signal Handshake and timeout, fallback with Retry and Open in new tab, and a reason: slow or never answered
Loading loading="lazy" with no visible state Lazy with a skeleton and a state attribute for CSS
Security Write sandbox by hand strict / standard / trusted presets, origin allowlists per frame and per method
Theme Content knows nothing about the page Light/dark theme synced into the child

Install

npm

npm install matframe
import 'matframe'; // registers <mat-frame> and window.MatFrame

In SSR frameworks (Next.js, Nuxt, SvelteKit) import it on the client only, for example inside useEffect or onMount.

CDN

<script src="https://cdn.jsdelivr.net/npm/matframe@0.1/matframe.min.js"></script>

Download โ€” copy matframe.js into your project and include it with a <script> tag.

The same file is used on both sides: the parent page (which shows <mat-frame>) and the embedded page (which calls MatFrame.child.init()).

Usage

Parent page

<mat-frame id="w"
  src="https://widget.example.com"
  origin="https://widget.example.com"
  auto-height lazy handshake
  sandbox="trusted" theme="dark" timeout="8000"></mat-frame>

<script>
  const w = document.getElementById('w');

  // functions the child can call
  w.expose({ save: (data) => api.save(data) });

  w.addEventListener('mf-ready', async () => {
    const info = await w.call('getInfo'); // Promise
    console.log(info);
  });
</script>

Embedded page (child)

<script src="matframe.js"></script>
<script>
  MatFrame.child
    .expose({ getInfo: () => ({ users: 42 }) })
    .onTheme((theme) => console.log('theme is now', theme))
    .init({ parentOrigins: ['https://your-site.com'] });

  // call the parent
  MatFrame.child.call('save', { name: 'Dima' }).then(console.log);
</script>

A complete runnable example is in examples/basic.

Frameworks

MatFrame is a standard custom element, so it works anywhere HTML works. For the most common stacks there are ready-made wrappers.

React

import { MatFrame } from 'matframe/react';
import { useMemo, useRef } from 'react';

export function Widget() {
  const frame = useRef(null);
  const handlers = useMemo(() => ({ save: (data) => api.save(data) }), []);

  return (
    <MatFrame
      ref={frame}
      src="https://widget.example.com"
      autoHeight
      lazy
      handshake
      theme="dark"
      handlers={handlers}
      onReady={async () => console.log(await frame.current.call('getInfo'))}
      onResize={({ height }) => console.log(height)}
      onError={({ reason }) => console.warn(reason)}
    />
  );
}

Works with React 17, 18 and 19 and with server-side rendering (it ships with 'use client' for the Next.js App Router). ref.current is the <mat-frame> element, so call, request, emit and reload are all available. Memoize handlers with useMemo.

Vue 3

<script setup>
import { ref } from 'vue';
import { MatFrame } from 'matframe/vue';

const frame = ref();
const handlers = { save: (data) => api.save(data) };
async function onReady() { console.log(await frame.value.call('getInfo')); }
</script>

<template>
  <MatFrame ref="frame" src="https://widget.example.com" auto-height lazy handshake theme="dark"
    :handlers="handlers" @ready="onReady" @resize="({ height }) => console.log(height)" />
</template>

Events: @state, @load, @ready, @resize, @message, @error. To register it globally: app.use(MatFramePlugin).

If you prefer the raw <mat-frame> tag in Vue templates, tell Vue it's a custom element: compilerOptions: { isCustomElement: (tag) => tag === 'mat-frame' } in your Vite Vue plugin options.

Angular

// main.ts
import 'matframe';
@Component({
  standalone: true,
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  template: `<mat-frame #frame [attr.src]="url" auto-height handshake (mf-ready)="onReady()"></mat-frame>`
})
export class WidgetComponent {
  @ViewChild('frame', { static: true }) frame!: ElementRef<MatFrameElement>;
  async onReady() { console.log(await this.frame.nativeElement.call('getInfo')); }
}

Bind with [attr.src], [attr.theme] and so on: MatFrame reads attributes, not properties. Events use their DOM names: (mf-ready), (mf-resize), (mf-error). A complete example is in integrations/angular.

PHP

composer require bossartemii/matframe
use MatFrame\MatFrame;

echo MatFrame::script();
echo MatFrame::tag('https://widget.example.com', ['auto-height' => true, 'lazy' => true, 'theme' => 'dark']);

// In the embedded page:
echo MatFrame::child(['https://your-site.com']);

Every value is escaped. true prints a bare attribute, false and null leave it out, arrays (like origin) are joined with spaces. Works with Laravel, Symfony, WordPress or plain PHP 7.4+.

Svelte, Solid, Astro, plain HTML

Use the tag directly after import 'matframe' (or the CDN script): these frameworks pass attributes and DOM events to custom elements natively.

Recipes

Chat or support widget. Let the widget grow with the conversation, and open it from your own button:

const chat = document.querySelector('mat-frame#chat');
document.querySelector('#help').onclick = () => chat.emit('open', { user: currentUser.name });
chat.addEventListener('mf-message', (e) => { if (e.detail.name === 'unread') badge.textContent = e.detail.data; });

Checkout or payment step. Only the checkout origin may report a payment, and slow calls can be cancelled when the user leaves:

frame.expose({ paid: (order) => showReceipt(order) }, { origins: ['https://checkout.example.com'] });
const ctrl = new AbortController();
leaveButton.onclick = () => ctrl.abort();
const quote = await frame.request('getQuote', [cartId], { signal: ctrl.signal, timeout: 5000 });

Live preview (CMS, email builder, docs). Send the draft into the preview and let it size itself:

<mat-frame id="preview" src="/preview.html" auto-height sandbox="strict"></mat-frame>
<script>
  editor.on('change', (html) => preview.emit('render', html));
</script>

Third-party embed you don't control. No child script and no handshake (it would never arrive): you still get lazy loading, a skeleton, and a fallback with Open in new tab if the page doesn't load in time. A page that refuses to be framed can't be detected without the child script, see Limits.

<mat-frame src="https://example.com/embed" lazy timeout="8000"></mat-frame>

Attributes

Attribute Default What it does
src / srcdoc โ€” Content to load, as on <iframe>. Changing it reloads.
auto-height off Resize to the content height.
min-height / max-height โ€” Limits for auto-height, in px.
lazy off Start loading when the frame is near the viewport.
lazy-margin 200px How early lazy starts.
handshake off Wait for the child's init(); show the fallback if it never arrives.
timeout 10000 Milliseconds to wait for the document to load before the fallback (reason timeout).
handshake-grace 2000 With handshake: milliseconds after load to wait for init() before the fallback (reason no-handshake).
sandbox standard strict, standard, trusted, none, or a raw sandbox string.
origin * One or more allowed child origins, space-separated. Messages from others are dropped. Set it in production.
theme โ€” Sent to the child; sets data-theme on its <html>.
call-timeout 5000 Default milliseconds before call() / request() rejects.
title, allow, referrerpolicy โ€” Passed to the inner iframe.

Sandbox presets:

  • strict โ†’ allow-scripts
  • standard โ†’ allow-scripts allow-forms allow-popups allow-modals
  • trusted โ†’ standard + allow-same-origin allow-downloads

To use origin, the child needs allow-same-origin (use trusted). Without it the browser gives the child the opaque origin "null", so a real origin can never match; MatFrame warns in the console. allow-scripts + allow-same-origin is safe for content from another origin; never combine them for same-origin content you don't trust.

JavaScript API

Element (<mat-frame>)

  • call(method, ...args) โ†’ Promise โ€” call a function exposed by the child.
  • request(method, args, { signal, timeout }) โ†’ Promise โ€” same, with an AbortSignal and a per-call timeout (0 = none).
  • expose({ name: fn }, { origins }) โ€” let the child call these functions (they may be async). origins limits which child origins may call them.
  • emit(name, data) โ€” send an event to the child.
  • reload() โ€” reload the content.
  • state โ€” idle, loading, ready or error (also mirrored as an attribute).
  • ready โ€” true after the child's handshake.
  • errorReason โ€” timeout or no-handshake while in the error state.
  • contentWindow โ€” the inner iframe's window.

Child (MatFrame.child)

  • init({ parentOrigins }) โ€” start: sends the handshake and reports the height. parentOrigins is an array or a single origin (parentOrigin also works).
  • expose({ name: fn }, { origins }), call(method, ...args), request(method, args, { signal, timeout }), emit(name, data)
  • on(name, fn) โ€” receive events sent with the parent's emit().
  • onTheme(fn) โ€” run when the parent's theme changes.

Inside a handler, on either side, this gives you:

  • this.signal โ€” an AbortSignal that fires when the caller aborts, times out, or the frame reloads or is removed.
  • this.origin โ€” the caller's origin.
  • this.frame โ€” the <mat-frame> element (parent side only).

Cancellation

const ctrl = new AbortController();
const result = frame.request('search', [query], { signal: ctrl.signal, timeout: 3000 });
ctrl.abort(); // rejects with AbortError; the child's handler sees this.signal abort

// in the child
MatFrame.child.expose({
  search(q) {
    return fetch('/api?q=' + q, { signal: this.signal }).then((r) => r.json());
  }
});

A cancelled call never resolves later: a result that arrives after the abort is ignored.

Trust boundaries per method

frame.expose({ getTheme: () => 'dark' });                                 // any allowed origin
frame.expose({ savePayment: (p) => pay(p) }, { origins: ['https://checkout.example.com'] });

Calls from other origins reject with Origin not allowed to call "savePayment".

Events

All events bubble and cross shadow DOM.

Event detail
mf-state { state }
mf-load โ€”
mf-ready โ€” (handshake done)
mf-resize { height }
mf-message { name, data } from the child's emit()
mf-error { message, reason } โ€” reason is timeout (never loaded) or no-handshake (loaded, never answered)

Styling

mat-frame { --mf-bg: #f1f3f5; --mf-ink: #111; --mf-radius: 12px; }
mat-frame[state="loading"] { opacity: .8; }
mat-frame::part(frame) { /* the inner iframe */ }
mat-frame::part(skeleton) { }
mat-frame::part(error) { }

Translating the texts

The fallback and error texts are in English. Change them once for the whole page:

Object.assign(MatFrame.strings, {
  retry: 'Riprova',
  open: 'Apri in nuova scheda โ†—',
  noReply: 'Il contenuto si รจ caricato ma non ha risposto.',
  slow: 'Il caricamento sta impiegando troppo.'
});

Limits (honestly)

  • Cross-origin auto-height and messaging need the child's cooperation. The embedded page must include matframe.js and call MatFrame.child.init(). Browsers do not let any script measure or control another site's page, by design. Same-origin content (with sandbox="trusted" or none) is resized without the child script.
  • A blocked page cannot be told apart from an incompatible one. Browsers still fire load for pages refused by X-Frame-Options or CSP frame-ancestors, and give no error you can read. With handshake, MatFrame separates two cases it can observe: the document never loaded (timeout, usually slow) and it loaded but never answered (no-handshake: blocked, or not using MatFrame). Both show Retry and Open in new tab. If a slow child answers late, the frame recovers by itself.
  • origin defaults to * so the demo works out of the box. In production, set origin on the parent and parentOrigins in the child.

Browser support

Current Chrome, Edge, Firefox and Safari (Custom Elements, Shadow DOM, ResizeObserver, IntersectionObserver).

Use with AI coding tools

Make Claude Code, Cursor, Windsurf, Copilot, Lovable, Bolt, v0 or Replit use <mat-frame> instead of <iframe> automatically: copy one ready-made rule file from integrations/. Agents that read the web can use llms.txt. TypeScript types are in matframe.d.ts.

Contributing

Issues and pull requests are welcome. See CONTRIBUTING.md. Security reports: SECURITY.md.

License

MIT