@sendsay-ru/guidely-frame-bridge
v0.7.2
Published
Cross-origin iframe target resolver for Guidely.
Maintainers
Readme
@sendsay-ru/guidely-frame-bridge
Cross-origin iframe target resolver for Guidely.
Use this package when a Guidely tour runs in a host application, but some step targets live inside a strict cross-origin iframe. The host cannot read iframe DOM directly, so the bridge exchanges a small postMessage protocol with a cooperating script inside the iframe.
The protocol only transfers target status, rectangles, and target events. It never transfers DOM nodes or user-authored HTML.
The child announces when its bridge is ready. If the parent subscribed before the child installed its message listener or the iframe reloads, the parent restores availability, rectangle, and target event subscriptions after the readiness handshake.
Install
yarn add @sendsay-ru/guidely-frame-bridge@sendsay-ru/guidely is a peer dependency.
Quick Start
Parent application:
import { createGuidely } from "@sendsay-ru/guidely";
import { createFrameTargetResolver } from "@sendsay-ru/guidely-frame-bridge";
const iframe = document.querySelector<HTMLIFrameElement>("#email-builder-frame");
if (!iframe) {
throw new Error("Email builder iframe was not found");
}
const frameTargets = createFrameTargetResolver({
iframe,
bridgeId: "account-email-builder",
scope: "frame",
targetOrigin: "https://builder.example.com",
allowedOrigins: ["https://builder.example.com"],
timeout: 1000,
});
const guidely = createGuidely({
config,
adapter,
targetResolver: frameTargets,
});Iframe application:
import { connectGuidelyFrameBridge } from "@sendsay-ru/guidely-frame-bridge";
const disconnectGuidely = connectGuidelyFrameBridge({
bridgeId: "account-email-builder",
targetOrigin: "https://account.example.com",
allowedOrigins: ["https://account.example.com"],
attributePrefix: "guidely",
});Targets inside the iframe use the same Guidely target config:
<input data-guidely-id="email-subject" /> <button data-guidely-id="send-test">Send test</button>const config = {
version: 1,
flows: [
{
id: "builder-tour",
steps: [
{
id: "subject",
type: "tooltip",
target: { type: "data-id", value: "email-subject", scope: "frame" },
content: { en: { body: "This target is inside the iframe." } },
},
{
id: "send-test",
type: "tooltip",
target: { type: "data-id", value: "send-test", scope: "frame" },
advanceOn: { event: "click" },
content: { en: { body: "Click inside the iframe to continue." } },
},
],
},
],
};Mixed Host and Iframe Targets
Guidely core composes custom target resolvers with the default DOM resolver. That means a single host Guidely instance can resolve:
- regular host application targets through
data-guidely-idor CSS selectors; - iframe targets through
createFrameTargetResolver.
No manual resolver composition is required for the common one-iframe setup.
Use explicit scopes for deterministic routing: host targets normally use scope: "document", and
iframe targets use the same scope passed to the frame resolver. Unscoped targets are accepted for
backwards compatibility.
Parent API
createFrameTargetResolver(options)
Creates a Guidely targetResolver for the parent application.
const resolver = createFrameTargetResolver({
iframe,
bridgeId,
scope,
targetOrigin,
allowedOrigins,
timeout,
});Options:
iframe: the iframe element containing the child application.bridgeId: shared identifier used by parent and child to reject unrelated messages.scope: target scope handled by this resolver. Defaults toframe.targetOrigin: exact origin used when posting messages to the iframe.*is rejected.allowedOrigins: origins accepted from incoming iframe messages. Defaults to[targetOrigin].timeout: request timeout in milliseconds. Defaults to1000.window: optional window override, mainly for tests.
Return value:
- A
TTargetResolvercompatible object. destroy(): removes parent message listeners and clears pending requests.
createDynamicFrameTargetResolver(options)
Use the dynamic resolver when the iframe is mounted lazily or replaced by the host application. It owns iframe discovery, origin derivation, bridge recreation, and availability re-subscription.
import { createDynamicFrameTargetResolver } from "@sendsay-ru/guidely-frame-bridge";
const resolver = createDynamicFrameTargetResolver({
iframe: "#email-builder-frame",
bridgeId: "account-email-builder",
scope: "frame",
});iframe can be a CSS selector or a function returning the current iframe. By default the exact
target origin is derived from the iframe src; pass a fixed string or resolver function through
targetOrigin to override it. allowedOrigins can likewise be a fixed list or a function. The
resolver reports targets unavailable while no valid iframe exists and reconnects automatically
when the iframe or its src changes. Call destroy() during host cleanup.
Prefer a stable id selector such as #email-builder-frame, or a stable id-rooted path such as
#editor-container iframe. The dynamic resolver can then ignore unrelated host DOM mutations and
observe only id and src changes. Other selectors and resolver functions are supported, but are
re-queried conservatively after child-tree and iframe src mutations. Invalid selectors and
selectors resolving to non-iframe elements are treated as temporarily unavailable.
Child API
connectGuidelyFrameBridge(options)
Connects the iframe application to the parent resolver.
const cleanup = connectGuidelyFrameBridge({
bridgeId,
targetOrigin,
allowedOrigins,
attributePrefix,
});Options:
bridgeId: same value as the parent resolver.targetOrigin: exact parent origin used when posting messages.*is rejected.allowedOrigins: origins accepted from incoming parent messages. Defaults to[targetOrigin].attributePrefix: prefix fordata-${prefix}-idtargets. Defaults toguidely.window,document,parentWindow: optional overrides, mainly for tests.
Return value:
- A cleanup function that removes listeners, observers, and event subscriptions.
Target Picking
Parent resolvers implement startPicking(listener), so visual editors such as
@sendsay-ru/guidely-editor can let authors pick targets inside the iframe. While picking:
- the child reports the element under the pointer and the clicked element, but only elements
marked with
data-<attributePrefix>-id, and only their id and rectangle; - clicks inside the iframe do not reach the application;
- Escape inside the iframe cancels picking.
The parent reports candidates in parent viewport coordinates, clipped to the iframe, with the
resolver scope set on the target. createDynamicFrameTargetResolver keeps picking when the iframe
is replaced, and a reloaded child resumes picking after the readiness handshake.
Protocol and Security
Every message includes:
source:@sendsay-ru/guidely-frame-bridge;version: protocol version;bridgeId: shared parent/child bridge identifier;requestId: per-message request identifier.
The bridge validates:
- explicit
targetOrigin; wildcard origins are rejected; event.originagainstallowedOrigins;event.sourceagainst the expected frame or parent window;bridgeId;- protocol version;
- required protocol fields.
Protocol version 2 separates target presence from geometry:
availability-subscribe/update/unsubscribereports onlyfound/not-foundtransitions;rect-request/responseis a one-shot geometry lookup and is not retained;rect-subscribe/update/unsubscribeexists only while rendered UI tracks geometry;- event subscriptions have their own explicit lifecycle;
pick:start/stopfrom the parent andpick:hover/select/cancelfrom the child exist only while an author picks a target. Peers that do not know them ignore them.
Messages carry only:
- bridge readiness;
- target selectors from the Guidely config;
rectvalues in iframe viewport coordinates;statusvalues;- target event names;
- data-id values of elements an author hovers or picks while picking.
The parent accepts only data-id candidates from the child.
The parent converts iframe-local rects to parent viewport coordinates by adding iframe.getBoundingClientRect().
Updates and performance
The child resolves targets with the same rules as the DOM resolver in @sendsay-ru/guidely: a
target is available only while it is rendered, which means it has a non-empty layout box and is not
hidden with visibility. When several elements match, the first rendered one is used and kept
while it stays rendered.
The child keeps one shared DOM MutationObserver, and only while availability or rect
subscriptions exist. Unchanged availability and identical rectangles are deduplicated before
postMessage; a one-shot missing-target request cannot create a permanent watch or an idle
not-found loop.
Idle data-id availability subscriptions observe only the configured
data-<attributePrefix>-id attribute and inspect added subtrees only when they can contain a
requested target. This keeps unrelated analytics, accessibility, style, and application DOM churn
off the message path. A ResizeObserver on the chosen elements, or on the candidates while a
target is missing, notices targets shown or hidden with display. CSS availability selectors
require broader observation; prefer data-id targets for auto-promotion. Attribute observation
becomes conservative only while an active rect subscription must track layout-sensitive changes.
For active rect subscriptions, the child checks updates after:
- iframe document scroll;
- iframe window resize;
- DOM mutations;
- target
ResizeObserverchanges when available.
The parent resolver also watches the iframe element position, so a host-page scroll or iframe movement updates the final parent-viewport rect.
Incoming messages are validated by concrete message type, including target shape, subscription fields, status, and finite rectangle coordinates. Unknown or malformed messages are ignored.
Target event subscriptions in the child are bound to the target config, not to one element. They keep working when the target appears after the subscription or the iframe application re-mounts it with the same id.
Always call the returned unsubscribe functions and destroy() when their owners unmount. The
bridge sends explicit unsubscribe messages and disconnects observers when the final subscriber is
removed.
Example
See examples/frame-bridge for a runnable parent + iframe demo.
