Skip to content

Beautiful Open-Source Form Builder

Implement editor embed bridge for form events

Chirag Chhatrala164efc7c6c30
diff --git a/client/components/open/forms/components/FormEditor.vue b/client/components/open/forms/components/FormEditor.vue
index c15a81e9d..cbef4e917 100644
--- a/client/components/open/forms/components/FormEditor.vue
+++ b/client/components/open/forms/components/FormEditor.vue
@@ -168,6 +168,8 @@ const showLogicConfirmationModal = ref(false)
const validationErrorResponse = ref(null)
const createdFormSlug = ref(null)
const logicErrors = ref([])
+const route = useRoute()
+const { emitFormSaved, emitNavigateBack } = useEditorEmbedBridge()
// Sidebar resizing using composable
const {
@@ -238,10 +240,13 @@ const activeTab = computed(() => workingFormStore.activeTab)
// Methods
const goBack = () => {
+ const toRoute = props.isEdit ? 'forms-slug-show-submissions' : 'home'
+ emitNavigateBack(route.name, toRoute)
+
if (props.isEdit) {
- useRouter().push({ name: 'forms-slug-show-submissions', params: {slug: form.value.slug} })
+ useRouter().push({ name: toRoute, params: { slug: form.value.slug } })
} else {
- useRouter().push({ name: 'home' })
+ useRouter().push({ name: toRoute })
}
}
@@ -312,6 +317,7 @@ const saveFormEdit = () => {
form.value.mutate(updateMutation).then((response) => {
const updatedForm = response.form
emit("on-save")
+ emitFormSaved(updatedForm, { isNew: false })
// Navigate to share page
useRouter().push({
@@ -369,6 +375,7 @@ const saveFormCreate = () => {
const newForm = response.form
emit("on-save")
createdFormSlug.value = newForm.slug
+ emitFormSaved(newForm, { isNew: true })
try{
// Analytics / alerts
diff --git a/client/components/pages/forms/show/ExtraMenu.vue b/client/components/pages/forms/show/ExtraMenu.vue
index ac22d9df2..6cbc16132 100644
--- a/client/components/pages/forms/show/ExtraMenu.vue
+++ b/client/components/pages/forms/show/ExtraMenu.vue
@@ -94,6 +94,7 @@ const showFormWorkspaceModal = ref(false)
const deleteFormMutation = remove()
const duplicateFormMutation = duplicate()
+const { emitFormDeleted } = useEditorEmbedBridge()
const items = computed(() => {
return [
@@ -179,6 +180,7 @@ const deleteForm = () => {
deleteFormMutation.mutateAsync(props.form.id).then((data) => {
useAlert().success(data.message)
showDeleteFormModal.value = false
+ emitFormDeleted(props.form)
router.push({ name: "home" })
}).catch((error) => {
useAlert().error(error.data?.message || "Failed to delete form")
diff --git a/client/composables/useEditorEmbedBridge.js b/client/composables/useEditorEmbedBridge.js
new file mode 100644
index 000000000..12dedeb86
--- /dev/null
+++ b/client/composables/useEditorEmbedBridge.js
@@ -0,0 +1,13 @@
+import {
+ emitEditorFormDeleted,
+ emitEditorFormSaved,
+ emitEditorNavigateBack,
+} from '~/lib/sdk/editorEmbedBridge'
+
+export function useEditorEmbedBridge() {
+ return {
+ emitFormSaved: emitEditorFormSaved,
+ emitFormDeleted: emitEditorFormDeleted,
+ emitNavigateBack: emitEditorNavigateBack,
+ }
+}
diff --git a/client/lib/sdk/editorEmbedBridge.js b/client/lib/sdk/editorEmbedBridge.js
new file mode 100644
index 000000000..76d43405c
--- /dev/null
+++ b/client/lib/sdk/editorEmbedBridge.js
@@ -0,0 +1,115 @@
+import {
+ resolveInitialTrustedOrigin,
+ WILDCARD_ORIGIN,
+} from './sdkBridgeMessaging.js'
+
+export const EDITOR_MSG_TYPE = 'opnform:editor:event'
+
+export const EDITOR_EVENTS = {
+ FORM_SAVED: 'formSaved',
+ FORM_DELETED: 'formDeleted',
+ NAVIGATE_BACK: 'navigateBack',
+}
+
+const ROUTE_VIEW_MAP = {
+ home: 'forms_list',
+ 'forms-create': 'create_form',
+ 'forms-slug-edit': 'edit_form',
+ 'forms-slug-show-submissions': 'submissions',
+ 'forms-slug-show-share': 'share',
+ 'forms-slug-show-integrations': 'integrations',
+ 'forms-slug-show-stats': 'stats',
+ 'forms-slug-show-summary': 'summary',
+ 'forms-slug-show-pdf-templates': 'pdf_templates',
+}
+
+function isEmbeddedInIframe() {
+ if (typeof window === 'undefined') return false
+ return window.location !== window.parent.location || window.frameElement !== null
+}
+
+function getPostTargetOrigin() {
+ return resolveInitialTrustedOrigin(isEmbeddedInIframe()) || WILDCARD_ORIGIN
+}
+
+function toPlainObject(value) {
+ if (value === null || value === undefined) return value
+
+ try {
+ return JSON.parse(JSON.stringify(value))
+ } catch {
+ return {}
+ }
+}
+
+function normalizeFormPayload(form) {
+ if (!form) return null
+
+ return {
+ id: form.id,
+ slug: form.slug,
+ title: form.title,
+ visibility: form.visibility,
+ }
+}
+
+export function resolveEditorView(routeName) {
+ if (!routeName) return null
+ return ROUTE_VIEW_MAP[routeName] || routeName
+}
+
+export function resolveEditorRouteView(routeName) {
+ return {
+ view: resolveEditorView(routeName),
+ route: routeName,
+ }
+}
+
+function postMessageSafe(target, message, origin) {
+ try {
+ target.postMessage(message, origin || WILDCARD_ORIGIN)
+ } catch (error) {
+ if (error?.name !== 'DataCloneError') {
+ console.error('[OpnForm Editor Embed] postMessage failed:', error)
+ }
+ }
+}
+
+/**
+ * Sends an editor embed event to the parent window when running inside an iframe.
+ */
+export function emitEditorEvent(event, payload = {}) {
+ if (typeof window === 'undefined') return
+
+ const message = {
+ type: EDITOR_MSG_TYPE,
+ event,
+ payload: toPlainObject(payload),
+ }
+
+ if (isEmbeddedInIframe()) {
+ postMessageSafe(window.parent, message, getPostTargetOrigin())
+ }
+
+ postMessageSafe(window, message, window.location.origin)
+}
+
+export function emitEditorFormSaved(form, { isNew = false } = {}) {
+ emitEditorEvent(EDITOR_EVENTS.FORM_SAVED, {
+ form: normalizeFormPayload(form),
+ isNew,
+ })
+}
+
+export function emitEditorFormDeleted(form) {
+ emitEditorEvent(EDITOR_EVENTS.FORM_DELETED, {
+ form: normalizeFormPayload(form),
+ })
+}
+
+export function emitEditorNavigateBack(fromRouteName, toRouteName) {
+ emitEditorEvent(EDITOR_EVENTS.NAVIGATE_BACK, {
+ from: resolveEditorRouteView(fromRouteName),
+ to: resolveEditorRouteView(toRouteName),
+ })
+}
diff --git a/client/lib/sdk/index.js b/client/lib/sdk/index.js
index c5627ce75..6951dea47 100644
--- a/client/lib/sdk/index.js
+++ b/client/lib/sdk/index.js
@@ -4,4 +4,14 @@
*/
export { useSdkBridge, createLocalSDK, OpnFormLocalSDK, EVENTS } from './useSdkBridge'
+export {
+ EDITOR_EVENTS,
+ EDITOR_MSG_TYPE,
+ emitEditorEvent,
+ emitEditorFormDeleted,
+ emitEditorFormSaved,
+ emitEditorNavigateBack,
+ resolveEditorRouteView,
+ resolveEditorView,
+} from './editorEmbedBridge'
diff --git a/client/test/unit/editor-embed-bridge.test.ts b/client/test/unit/editor-embed-bridge.test.ts
new file mode 100644
index 000000000..5bd580c34
--- /dev/null
+++ b/client/test/unit/editor-embed-bridge.test.ts
@@ -0,0 +1,215 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { JSDOM } from 'jsdom'
+import {
+ EDITOR_EVENTS,
+ EDITOR_MSG_TYPE,
+ emitEditorEvent,
+ emitEditorFormDeleted,
+ emitEditorFormSaved,
+ emitEditorNavigateBack,
+ resolveEditorRouteView,
+ resolveEditorView,
+} from '../../lib/sdk/editorEmbedBridge.js'
+
+const PARENT_ORIGIN = 'https://cms.example.test'
+const EDITOR_ORIGIN = 'https://opnform.example.test'
+
+function installIframeWindow(dom: JSDOM, search = '') {
+ const { window } = dom
+ const mockParent = {
+ postMessage: vi.fn(),
+ }
+
+ Object.defineProperty(window, 'parent', {
+ configurable: true,
+ value: mockParent,
+ })
+
+ Object.defineProperty(window, 'frameElement', {
+ configurable: true,
+ value: {},
+ })
+
+ window.history.replaceState({}, '', `${window.location.pathname}${search}`)
+
+ return { window, mockParent }
+}
+
+describe('editor embed bridge', () => {
+ let dom: JSDOM
+ let mockParent: { postMessage: ReturnType<typeof vi.fn> }
+ let windowMessages: Array<{ message: unknown, origin: string }>
+
+ beforeEach(() => {
+ dom = new JSDOM('<!doctype html><html><body></body></html>', {
+ url: `${EDITOR_ORIGIN}/forms/demo-form/edit`,
+ })
+
+ const installed = installIframeWindow(dom)
+ mockParent = installed.mockParent
+ windowMessages = []
+
+ vi.spyOn(dom.window, 'postMessage').mockImplementation((message: unknown, origin: string) => {
+ windowMessages.push({ message, origin })
+ })
+
+ vi.stubGlobal('window', dom.window)
+ vi.stubGlobal('document', dom.window.document)
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ describe('resolveEditorView', () => {
+ it('maps known route names to stable view identifiers', () => {
+ expect(resolveEditorView('home')).toBe('forms_list')
+ expect(resolveEditorView('forms-slug-edit')).toBe('edit_form')
+ expect(resolveEditorView('forms-slug-show-submissions')).toBe('submissions')
+ })
+
+ it('falls back to the route name for unknown routes', () => {
+ expect(resolveEditorView('custom-route')).toBe('custom-route')
+ })
+
+ it('returns null when route name is missing', () => {
+ expect(resolveEditorView(null)).toBeNull()
+ })
+ })
+
+ describe('resolveEditorRouteView', () => {
+ it('returns both view and route fields', () => {
+ expect(resolveEditorRouteView('forms-slug-edit')).toEqual({
+ view: 'edit_form',
+ route: 'forms-slug-edit',
+ })
+ })
+ })
+
+ describe('emitEditorEvent', () => {
+ it('posts to parent and current window with the editor message type', () => {
+ emitEditorEvent('testEvent', { foo: 'bar' })
+
+ expect(mockParent.postMessage).toHaveBeenCalledWith(
+ {
+ type: EDITOR_MSG_TYPE,
+ event: 'testEvent',
+ payload: { foo: 'bar' },
+ },
+ '*',
+ )
+
+ expect(windowMessages).toContainEqual({
+ message: {
+ type: EDITOR_MSG_TYPE,
+ event: 'testEvent',
+ payload: { foo: 'bar' },
+ },
+ origin: EDITOR_ORIGIN,
+ })
+ })
+
+ it('uses _sdkParentOrigin when provided in the iframe URL', () => {
+ const installed = installIframeWindow(dom, `?_sdkParentOrigin=${encodeURIComponent(PARENT_ORIGIN)}`)
+
+ emitEditorEvent('testEvent', {})
+
+ expect(installed.mockParent.postMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ type: EDITOR_MSG_TYPE }),
+ PARENT_ORIGIN,
+ )
+ })
+
+ it('does not post to parent when not embedded in an iframe', () => {
+ Object.defineProperty(dom.window, 'parent', {
+ configurable: true,
+ value: dom.window,
+ })
+ Object.defineProperty(dom.window, 'frameElement', {
+ configurable: true,
+ value: null,
+ })
+
+ emitEditorEvent('testEvent', {})
+
+ expect(mockParent.postMessage).not.toHaveBeenCalled()
+ expect(windowMessages).toHaveLength(1)
+ })
+ })
+
+ describe('named emit helpers', () => {
+ it('emits formSaved with normalized form payload', () => {
+ emitEditorFormSaved({
+ id: 1,
+ slug: 'demo-form',
+ title: 'Demo',
+ visibility: 'public',
+ extra: 'ignored',
+ }, { isNew: true })
+
+ expect(mockParent.postMessage).toHaveBeenCalledWith(
+ {
+ type: EDITOR_MSG_TYPE,
+ event: EDITOR_EVENTS.FORM_SAVED,
+ payload: {
+ form: {
+ id: 1,
+ slug: 'demo-form',
+ title: 'Demo',
+ visibility: 'public',
+ },
+ isNew: true,
+ },
+ },
+ '*',
+ )
+ })
+
+ it('emits formDeleted with normalized form payload', () => {
+ emitEditorFormDeleted({
+ id: 2,
+ slug: 'old-form',
+ title: 'Old',
+ visibility: 'draft',
+ })
+
+ expect(mockParent.postMessage).toHaveBeenCalledWith(
+ {
+ type: EDITOR_MSG_TYPE,
+ event: EDITOR_EVENTS.FORM_DELETED,
+ payload: {
+ form: {
+ id: 2,
+ slug: 'old-form',
+ title: 'Old',
+ visibility: 'draft',
+ },
+ },
+ },
+ '*',
+ )
+ })
+
+ it('emits navigateBack with from and to route views', () => {
+ emitEditorNavigateBack('forms-slug-edit', 'forms-slug-show-submissions')
+
+ expect(mockParent.postMessage).toHaveBeenCalledWith(
+ {
+ type: EDITOR_MSG_TYPE,
+ event: EDITOR_EVENTS.NAVIGATE_BACK,
+ payload: {
+ from: {
+ view: 'edit_form',
+ route: 'forms-slug-edit',
+ },
+ to: {
+ view: 'submissions',
+ route: 'forms-slug-show-submissions',
+ },
+ },
+ },
+ '*',
+ )
+ })
+ })
+})
diff --git a/docs/docs.json b/docs/docs.json
index 41bfae2b3..c257dd5c3 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -65,7 +65,8 @@
{
"group": "Embedding",
"pages": [
- "embedding/javascript-sdk"
+ "embedding/javascript-sdk",
+ "embedding/editor-embed"
]
}
]
diff --git a/docs/embedding/editor-embed.mdx b/docs/embedding/editor-embed.mdx
new file mode 100644
index 000000000..cccaa2ad0
--- /dev/null
+++ b/docs/embedding/editor-embed.mdx
@@ -0,0 +1,98 @@
+---
+title: "Editor Embed Events"
+description: "Listen to postMessage events from the OpnForm form editor when embedded in your CMS or application"
+---
+
+When you embed the OpnForm **form editor** in an iframe (for example inside a headless CMS), the editor sends `postMessage` events to the parent window so you can react to save, delete, and back-navigation actions.
+
+<Warning>
+Editor embedding is available only to approved OpnForm partners with a signed agreement. If OpnForm has not enabled this option for your organization, embedding the editor on your site will not work. To discuss partner access, contact [[email protected]](mailto:[email protected]).
+</Warning>
+
+<Note>
+These events are separate from the [JavaScript SDK](/embedding/javascript-sdk) events used for **public form** embeds (`submit`, `pageChange`, etc.).
+</Note>
+
+## Message format
+
+All editor events use this structure:
+
+```javascript
+{
+ type: 'opnform:editor:event',
+ event: 'formSaved' | 'formDeleted' | 'navigateBack',
+ payload: { /* event-specific data */ }
+}
+```
+
+## Events
+
+| Event | When it fires | Payload |
+| ----- | ------------- | ------- |
+| `formSaved` | Editor save succeeds (create or update) | `{ form: { id, slug, title, visibility }, isNew: boolean }` |
+| `formDeleted` | Form is permanently deleted | `{ form: { id, slug, title, visibility } }` |
+| `navigateBack` | Editor navbar back button is clicked | `{ from: { view, route }, to: { view, route } }` |
+
+### View identifiers
+
+The `view` field in `navigateBack` payloads uses stable, human-readable IDs:
+
+| Route name | `view` |
+| ---------- | ------ |
+| `home` | `forms_list` |
+| `forms-create` | `create_form` |
+| `forms-slug-edit` | `edit_form` |
+| `forms-slug-show-submissions` | `submissions` |
+| `forms-slug-show-share` | `share` |
+| `forms-slug-show-integrations` | `integrations` |
+| `forms-slug-show-stats` | `stats` |
+| `forms-slug-show-summary` | `summary` |
+| `forms-slug-show-pdf-templates` | `pdf_templates` |
+| (unknown) | raw route name |
+
+## Parent listener example
+
+```javascript
+window.addEventListener('message', (event) => {
+ // Restrict to your OpnForm origin in production
+ if (event.origin !== 'https://your-opnform-domain.com') return
+
+ const { type, event: action, payload } = event.data || {}
+ if (type !== 'opnform:editor:event') return
+
+ switch (action) {
+ case 'formSaved':
+ console.log('Form saved:', payload.form.slug, payload.isNew ? '(new)' : '(updated)')
+ break
+ case 'formDeleted':
+ console.log('Form deleted:', payload.form.id)
+ break
+ case 'navigateBack':
+ console.log('Navigating back:', payload.from.view, '→', payload.to.view)
+ break
+ }
+})
+```
+
+## Origin targeting
+
+By default, messages are sent to the parent with target origin `*`. For stricter security, pass your CMS origin as a query parameter on the iframe URL:
+
+```
+https://your-opnform-domain.com/forms/my-form/edit?_sdkParentOrigin=https%3A%2F%2Fyour-cms.com
+```
+
+The editor will then post messages only to that origin.
+
+## Embedding the editor
+
+Embed authenticated editor pages directly in an iframe:
+
+```html
+<iframe
+ src="https://your-opnform-domain.com/forms/my-form/edit?_sdkParentOrigin=https%3A%2F%2Fyour-cms.com"
+ style="border:none;width:100%;height:100vh;"
+></iframe>
+```
+
+Your users must be authenticated with OpnForm (session cookie) for editor pages to load.