Skip to content

Beautiful Open-Source Form Builder

Support full form URLs and baseUrl in SDK create (#1308)

Julien Nahum54545c1cdb8b
diff --git a/client/README.md b/client/README.md
index f5db2a2db..662c39268 100644
--- a/client/README.md
+++ b/client/README.md
@@ -73,3 +73,17 @@ bun run preview
```
Check out the [deployment documentation](https://nuxt.com/docs/getting-started/deployment) for more information.
+
+## Public JavaScript SDK
+
+Edit `public/widgets/opnform-sdk.js`, then regenerate the committed minified
+asset before testing or committing:
+
+```bash
+npm run build:sdk
+```
+
+This uses esbuild to write `public/widgets/opnform-sdk.min.js` and preserves
+the SDK and bundled iFrame Resizer license comments. Do not edit the minified
+file directly. The production build, E2E build, and static generation commands
+also run this step before Nuxt copies the public assets.
diff --git a/client/package.json b/client/package.json
index 25c1a0ca6..0eae42010 100644
--- a/client/package.json
+++ b/client/package.json
@@ -3,11 +3,12 @@
"private": true,
"type": "module",
"scripts": {
- "build": "NODE_OPTIONS='--max-old-space-size=8192' nuxt build && npm run check:public-form-bundle",
- "build:e2e": "E2E=1 NODE_OPTIONS='--max-old-space-size=8192' nuxt build",
+ "build": "npm run build:sdk && NODE_OPTIONS='--max-old-space-size=8192' nuxt build && npm run check:public-form-bundle",
+ "build:e2e": "npm run build:sdk && E2E=1 NODE_OPTIONS='--max-old-space-size=8192' nuxt build",
+ "build:sdk": "esbuild public/widgets/opnform-sdk.js --minify --legal-comments=inline --banner:js='/* eslint-disable */' --outfile=public/widgets/opnform-sdk.min.js",
"dev": "export NODE_TLS_REJECT_UNAUTHORIZED=0; node --import ./scripts/node-localstorage-polyfill.mjs ./node_modules/nuxt/bin/nuxt.mjs dev",
"docker-dev": "export NODE_TLS_REJECT_UNAUTHORIZED=0; node --import ./scripts/node-localstorage-polyfill.mjs ./node_modules/nuxt/bin/nuxt.mjs dev --host 0.0.0.0",
- "generate": "export NODE_TLS_REJECT_UNAUTHORIZED=0; nuxt generate",
+ "generate": "npm run build:sdk && NODE_TLS_REJECT_UNAUTHORIZED=0 nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"test:ssr-cache:built": "node --test tests/ssr-config-cache-built.test.mjs",
diff --git a/client/public/widgets/opnform-sdk.js b/client/public/widgets/opnform-sdk.js
index ec2ddb200..df2f5b18a 100644
--- a/client/public/widgets/opnform-sdk.js
+++ b/client/public/widgets/opnform-sdk.js
@@ -1,5 +1,5 @@
/* eslint-disable */
-/**
+/*!
* OpnForm JavaScript SDK
* Enables programmatic interaction with embedded OpnForm forms
* Includes iFrame Resizer for automatic height adjustment
@@ -7,8 +7,9 @@
*/
// ============================================================================
-// iFrame Resizer v4.3.2 - (c) 2021 David J. Bradshaw - MIT License
-// https://github.com/davidjbradshaw/iframe-resizer
+/*! iFrame Resizer v4.3.2 - (c) 2021 David J. Bradshaw - MIT License
+ * https://github.com/davidjbradshaw/iframe-resizer
+ */
// ============================================================================
!function(e){var n,i,t,o,r,a,s,l,f,c,d,u,m,g;function h(){return window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver}function p(e,n,i){e.addEventListener(n,i,!1)}function b(e,n,i){e.removeEventListener(n,i,!1)}function y(e){return c[e]?c[e].log:i}function v(e,n){_("log",e,n,y(e))}function $(e,n){_("info",e,n,y(e))}function w(e,n){_("warn",e,n,!0)}function _(e,n,i,t){var o,a;!0===t&&"object"==typeof window.console&&console[e](r+"["+(a="Host page: "+(o=n),a=window.top!==window.self?window.parentIFrame&&window.parentIFrame.getId?window.parentIFrame.getId()+": "+o:"Nested host page: "+o:a)+"]",i)}function x(e){function n(){i("Height"),i("Width"),O(function(){E(j),I(L),h("onResized",j)},j,"init")}function i(e){var n=Number(c[L]["max"+e]),i=Number(c[L]["min"+e]),e=e.toLowerCase(),t=Number(j[e]);v(L,"Checking "+e+" is in range "+i+"-"+n),t<i&&(t=i,v(L,"Set "+e+" to min value")),n<t&&(t=n,v(L,"Set "+e+" to max value")),j[e]=""+t}function t(e){return P.slice(P.indexOf(":")+o+e)}function l(e,n){var i,t,o;i=function(){var i,t;T("Send Page Info","pageInfo:"+(i=document.body.getBoundingClientRect(),JSON.stringify({iframeHeight:(t=j.iframe.getBoundingClientRect()).height,iframeWidth:t.width,clientHeight:Math.max(document.documentElement.clientHeight,window.innerHeight||0),clientWidth:Math.max(document.documentElement.clientWidth,window.innerWidth||0),offsetTop:parseInt(t.top-i.top,10),offsetLeft:parseInt(t.left-i.left,10),scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,documentHeight:document.documentElement.clientHeight,documentWidth:document.documentElement.clientWidth,windowHeight:window.innerHeight,windowWidth:window.innerWidth})),e,n)},t=32,m[o=n]||(m[o]=setTimeout(function(){m[o]=null,i()},t))}function f(e){return e=e.getBoundingClientRect(),M(L),{x:Math.floor(Number(e.left)+Number(s.x)),y:Math.floor(Number(e.top)+Number(s.y))}}function d(e){var n=e?f(j.iframe):{x:0,y:0},i={x:Number(j.width)+n.x,y:Number(j.height)+n.y};v(L,"Reposition requested from iFrame (offset x:"+n.x+" y:"+n.y+")"),window.top===window.self?(s=i,u(),v(L,"--")):window.parentIFrame?window.parentIFrame["scrollTo"+(e?"Offset":"")](i.x,i.y):w(L,"Unable to scroll to requested position, window.parentIFrame not found")}function u(){!1===h("onScroll",s)?R():I(L)}function g(e){var n,i={};i=0===Number(j.width)&&0===Number(j.height)?{x:(n=t(9).split(":"))[1],y:n[0]}:{x:j.width,y:j.height},h(e,{iframe:j.iframe,screenX:Number(i.x),screenY:Number(i.y),type:j.type})}function h(e,n){return k(L,e,n)}var y,_,x,z,H,S,P=e.data,j={},L=null;if("[iFrameResizerChild]Ready"===P)for(var A in c)T("iFrame requested init",C(A),c[A].iframe,A);else r===(""+P).slice(0,a)&&P.slice(a).split(":")[0]in c?(c[L=(j=(_=(y=P.slice(a).split(":"))[1]?parseInt(y[1],10):0,z=getComputedStyle(x=c[y[0]]&&c[y[0]].iframe),{iframe:x,id:y[0],height:_+function(e){if("border-box"!==e.boxSizing)return 0;var n=e.paddingTop?parseInt(e.paddingTop,10):0,e=e.paddingBottom?parseInt(e.paddingBottom,10):0;return n+e}(z)+function(e){if("border-box"!==e.boxSizing)return 0;var n=e.borderTopWidth?parseInt(e.borderTopWidth,10):0,e=e.borderBottomWidth?parseInt(e.borderBottomWidth,10):0;return n+e}(z),width:y[2],type:y[3]})).id]&&(c[L].loaded=!0),(S=j.type in{true:1,false:1,undefined:1})&&v(L,"Ignoring init message from meta parent page"),!S&&(S=!0,c[H=L]||(S=!1,w(j.type+" No settings for "+H+". Message was: "+P)),S)&&(v(L,"Received: "+P),H=!0,null===j.iframe&&(w(L,"IFrame ("+j.id+") not found"),H=!1),H&&function n(){var i=e.origin,t=c[L]&&c[L].checkOrigin;if(t&&""+i!="null"&&!function(){if(t.constructor!==Array)return e=c[L]&&c[L].remoteHost,v(L,"Checking connection is from: "+e),i===e;var e,n=0,o=!1;for(v(L,"Checking connection is from allowed list of origins: "+t);n<t.length;n++)if(t[n]===i){o=!0;break}return o}())throw Error("Unexpected message received from: "+i+" for "+j.iframe.id+". Message was: "+e.data+". This error can be disabled by setting the checkOrigin: false option or by providing of array of trusted domains.");return 1}()&&function e(){var i,o,r,a,m;switch(c[L]&&c[L].firstRun&&c[L]&&(c[L].firstRun=!1),j.type){case"close":F(j.iframe);break;case"message":o=t(6),v(L,"onMessage passed: {iframe: "+j.iframe.id+", message: "+o+"}"),h("onMessage",{iframe:j.iframe,message:JSON.parse(o)}),v(L,"--");break;case"mouseenter":g("onMouseEnter");break;case"mouseleave":g("onMouseLeave");break;case"autoResize":c[L].autoResize=JSON.parse(t(9));break;case"scrollTo":d(!1);break;case"scrollToOffset":d(!0);break;case"pageInfo":l(c[L]&&c[L].iframe,L),i=L,y("Add ",p),c[i]&&(c[i].stopPageInfo=$);break;case"pageInfoStop":c[L]&&c[L].stopPageInfo&&(c[L].stopPageInfo(),delete c[L].stopPageInfo);break;case"inPageLink":t(9),m=decodeURIComponent(a=a.split("#")[1]||""),(m=document.getElementById(m)||document.getElementsByName(m)[0])?(m=f(m),v(L,"Moving to in page link (#"+a+") at x: "+m.x+" y: "+m.y),s={x:m.x,y:m.y},u(),v(L,"--")):window.top===window.self?v(L,"In page link #"+a+" not found"):window.parentIFrame?window.parentIFrame.moveToAnchor(a):v(L,"In page link #"+a+" not found and window.parentIFrame not found");break;case"reset":W(j);break;case"init":n(),h("onInit",j.iframe);break;default:0===Number(j.width)&&0===Number(j.height)?w("Unsupported message received ("+j.type+"), this is likely due to the iframe containing a later version of iframe-resizer than the parent page"):n()}function y(e,n){function t(){c[i]?l(c[i].iframe,i):$()}["scroll","resize"].forEach(function(o){v(i,e+o+" listener for sendPageInfo"),n(window,o,t)})}function $(){y("Remove ",b)}}())):$(L,"Ignored: "+P)}function k(e,n,i){var t=null,o=null;if(c[e]){if("function"!=typeof(t=c[e][n]))throw TypeError(n+" on iFrame["+e+"] is not a function");o=t(i)}return o}function z(e){delete c[e=e.id]}function F(e){var n=e.id;if(!1===k(n,"onClose",n))v(n,"Close iframe cancelled by onClose event");else{v(n,"Removing iFrame: "+n);try{e.parentNode&&e.parentNode.removeChild(e)}catch(i){w(i)}k(n,"onClosed",n),v(n,"--"),z(e)}}function M(n){null===s&&v(n,"Get page position: "+(s={x:window.pageXOffset===e?document.documentElement.scrollLeft:window.pageXOffset,y:window.pageYOffset===e?document.documentElement.scrollTop:window.pageYOffset}).x+","+s.y)}function I(e){null!==s&&(window.scrollTo(s.x,s.y),v(e,"Set page position: "+s.x+","+s.y),R())}function R(){s=null}function W(e){v(e.id,"Size reset requested by "+("init"===e.type?"host page":"iFrame")),M(e.id),O(function(){E(e),T("reset","reset",e.iframe,e.id)},e,"reset")}function E(e){function n(n){var o;o=n,e.id?(e.iframe.style[o]=e[o]+"px",v(e.id,"IFrame ("+i+") "+o+" set to "+e[o]+"px")):v("undefined","messageData id not set"),function n(o){var r;function a(){Object.keys(c).forEach(function(e){var n;function i(e){return"0px"===(c[n]&&c[n].iframe.style[e])}c[n=e]&&null!==c[n].iframe.offsetParent&&(i("height")||i("width"))&&T("Visibility change","resize",c[n].iframe,n)})}!t&&"0"===e[o]&&(t=!0,v(i,"Hidden iFrame detected, creating visibility listener"),o=h())&&(r=document.querySelector("body"),new o(function e(n){v("window","Mutation observed: "+n[0].target+" "+n[0].type),S(a,16)}).observe(r,{attributes:!0,attributeOldValue:!1,characterData:!0,characterDataOldValue:!1,childList:!0,subtree:!0}))}(n)}var i=e.iframe.id;c[i]&&(c[i].sizeHeight&&n("height"),c[i].sizeWidth)&&n("width")}function O(e,n,i){i!==n.type&&l&&!window.jasmine?(v(n.id,"Requesting animation frame"),l(e)):e()}function T(e,n,i,t,o){var a,s=!1;c[t=t||i.id]&&(i&&"contentWindow"in i&&null!==i.contentWindow?(a=c[t]&&c[t].targetOrigin,v(t,"["+e+"] Sending msg to iframe["+t+"] ("+n+") targetOrigin: "+a),i.contentWindow.postMessage(r+n,a)):w(t,"["+e+"] IFrame("+t+") not found"),o&&c[t]&&c[t].warningTimeout&&(c[t].msgTimeout=setTimeout(function(){!c[t]||c[t].loaded||s||(s=!0,w(t,"IFrame has not responded within "+c[t].warningTimeout/1e3+" seconds. Check iFrameResizer.contentWindow.js has been loaded in iFrame. This message can be ignored if everything is working, or you can set the warningTimeout option to a higher value or zero to suppress this warning."))},c[t].warningTimeout)))}function C(e){return e+":"+c[e].bodyMarginV1+":"+c[e].sizeWidth+":"+c[e].log+":"+c[e].interval+":"+c[e].enablePublicMethods+":"+c[e].autoResize+":"+c[e].bodyMargin+":"+c[e].heightCalculationMethod+":"+c[e].bodyBackground+":"+c[e].bodyPadding+":"+c[e].tolerance+":"+c[e].inPageLinks+":"+c[e].resizeFrom+":"+c[e].widthCalculationMethod+":"+c[e].mouseEvents}function H(t,o){function r(e){var n=e.split("Callback");2===n.length&&(this[n="on"+n[0].charAt(0).toUpperCase()+n[0].slice(1)]=this[e],delete this[e],w(l,"Deprecated: '"+e+"' has been renamed '"+n+"'. The old method will be removed in the next major version."))}var a,s,l=function(e){var r;if("string"!=typeof e)throw TypeError("Invaild id for iFrame. Expected String");return""===e&&(t.id=(r=o&&o.id||u.id+n++,null!==document.getElementById(r)&&(r+=n++),e=r),i=(o||{}).log,v(e,"Added missing iframe ID: "+e+" ("+t.src+")")),e}(t.id);if(l in c&&"iFrameResizer"in t)w(l,"Ignored iFrame, already setup.");else{switch(function e(n){if(n=n||{},c[l]=Object.create(null),c[l].iframe=t,c[l].firstRun=!0,c[l].remoteHost=t.src&&t.src.split("/").slice(0,3).join("/"),"object"!=typeof n)throw TypeError("Options is not an object");Object.keys(n).forEach(r,n);var i,o=n;for(i in u)Object.prototype.hasOwnProperty.call(u,i)&&(c[l][i]=(Object.prototype.hasOwnProperty.call(o,i)?o:u)[i]);c[l]&&(c[l].targetOrigin=!0!==c[l].checkOrigin||""===(n=c[l].remoteHost)||null!==n.match(/^(about:blank|javascript:|file:\/\/)/)?'*':n)}(o),v(l,"IFrame scrolling "+(c[l]&&c[l].scrolling?"enabled":"disabled")+" for "+l),t.style.overflow=!1===(c[l]&&c[l].scrolling)?"hidden":"auto",c[l]&&c[l].scrolling){case"omit":break;case!0:t.scrolling="yes";break;case!1:t.scrolling="no";break;default:t.scrolling=c[l]?c[l].scrolling:"no"}m("Height"),m("Width"),d("maxHeight"),d("minHeight"),d("maxWidth"),d("minWidth"),"number"!=typeof(c[l]&&c[l].bodyMargin)&&"0"!==(c[l]&&c[l].bodyMargin)||(c[l].bodyMarginV1=c[l].bodyMargin,c[l].bodyMargin=c[l].bodyMargin+"px"),a=C(l),(s=h())&&t.parentNode&&new s(function(e){e.forEach(function(e){Array.prototype.slice.call(e.removedNodes).forEach(function(e){e===t&&F(t)})})}).observe(t.parentNode,{childList:!0}),p(t,"load",function(){var n,i;T("iFrame.onload",a,t,e,!0),n=c[l]&&c[l].firstRun,i=c[l]&&c[l].heightCalculationMethod in f,!n&&i&&W({iframe:t,height:0,width:0,type:"init"})}),T("init",a,t,e,!0),c[l]&&(c[l].iframe.iFrameResizer={close:F.bind(null,c[l].iframe),removeListeners:z.bind(null,c[l].iframe),resize:T.bind(null,"Window resize","resize",c[l].iframe),moveToAnchor:function(e){T("Move to anchor","moveToAnchor:"+e,c[l].iframe,l)},sendMessage:function(e){T("Send Message","message:"+(e=JSON.stringify(e)),c[l].iframe,l)}})}function d(e){var n=c[l][e];1/0!==n&&0!==n&&(t.style[e]="number"==typeof n?n+"px":n,v(l,"Set "+e+" = "+t.style[e]))}function m(e){if(c[l]["min"+e]>c[l]["max"+e])throw Error("Value for min"+e+" can not be greater than max"+e)}}function S(e,n){null===d&&(d=setTimeout(function(){d=null,e()},n))}function P(){"hidden"!==document.visibilityState&&(v("document","Trigger event: Visibility change"),S(function(){j("Tab Visible","resize")},16))}function j(e,n){Object.keys(c).forEach(function(i){var t;c[t=i]&&"parent"===c[t].resizeFrom&&c[t].autoResize&&!c[t].firstRun&&T(e,n,c[i].iframe,i)})}function L(){function n(e,n){if(n){if(!n.tagName)throw TypeError("Object is not a valid DOM element");if("IFRAME"!==n.tagName.toUpperCase())throw TypeError("Expected <IFRAME> tag, found <"+n.tagName+">");H(n,e),i.push(n)}}for(var i,t=["moz","webkit","o","ms"],o=0;o<t.length&&!l;o+=1)l=window[t[o]+"RequestAnimationFrame"];return l?l=l.bind(window):v("setup","RequestAnimationFrame not supported"),p(window,"message",x),p(window,"resize",function(){var e;v("window","Trigger event: "+(e="resize")),S(function(){j("Window "+e,"resize")},16)}),p(document,"visibilitychange",P),p(document,"-webkit-visibilitychange",P),function(t,o){var r;switch(i=[],(r=t)&&r.enablePublicMethods&&w("enablePublicMethods option has been removed, public methods are now always available in the iFrame"),typeof o){case"undefined":case"string":Array.prototype.forEach.call(document.querySelectorAll(o||"iframe"),n.bind(e,t));break;case"object":n(t,o);break;default:throw TypeError("Unexpected data type ("+typeof o+")")}return i}}"undefined"!=typeof window&&(n=0,t=i=!1,o=7,a=(r="[iFrameSizer]").length,s=null,l=window.requestAnimationFrame,f=Object.freeze({max:1,scroll:1,bodyScroll:1,documentElementScroll:1}),c={},d=null,u=Object.freeze({autoResize:!0,bodyBackground:null,bodyMargin:null,bodyMarginV1:8,bodyPadding:null,checkOrigin:!0,inPageLinks:!1,enablePublicMethods:!0,heightCalculationMethod:"bodyOffset",id:"iFrameResizer",interval:32,log:!1,maxHeight:1/0,maxWidth:1/0,minHeight:0,minWidth:0,mouseEvents:!0,resizeFrom:"parent",scrolling:!1,sizeHeight:!0,sizeWidth:!1,warningTimeout:5e3,tolerance:0,widthCalculationMethod:"scroll",onClose:function(){return!0},onClosed:function(){},onInit:function(){},onMessage:function(){w("onMessage function not defined")},onMouseEnter:function(){},onMouseLeave:function(){},onResized:function(){},onScroll:function(){return!0}}),m={},window.jQuery!==e&&((g=window.jQuery).fn?g.fn.iFrameResize||(g.fn.iFrameResize=function(e){return this.filter("iframe").each(function(n,i){H(i,e)}).end()}):$("","Unable to bind to jQuery, it is not fully loaded.")),"function"==typeof define&&define.amd?define([],L):"object"==typeof module&&"object"==typeof module.exports&&(module.exports=L()),window.iFrameResize=window.iFrameResize||L())}();
@@ -591,8 +592,8 @@
return form ? form.isReady() : false
}
- create(slug, options = {}) {
- const { container, width = '100%', height = 'auto', darkMode, onSubmit } = options
+ create(slugOrUrl, options = {}) {
+ const { container, baseUrl = 'https://opnform.com', width = '100%', height = 'auto', darkMode, onSubmit } = options
let containerEl = container
if (typeof container === 'string') {
@@ -604,23 +605,34 @@
return null
}
+ let url
+ let slug
+ try {
+ if (typeof slugOrUrl !== 'string' || !slugOrUrl.trim()) throw new Error('Missing form slug or URL')
+ const isUrl = /^[a-z][a-z\d+.-]*:/i.test(slugOrUrl)
+ if (!isUrl && /[/?#\s]/.test(slugOrUrl)) throw new Error('Invalid form slug')
+ url = new URL(isUrl ? slugOrUrl : `${baseUrl.replace(/\/+$/, '')}/forms/${encodeURIComponent(slugOrUrl)}`)
+ const slugMatch = url.pathname.match(/\/forms\/([^/]+)\/?$/)
+ if (!['http:', 'https:'].includes(url.protocol) || !slugMatch) throw new Error('Invalid form URL')
+ slug = decodeURIComponent(slugMatch[1])
+ } catch (e) {
+ console.error('[OpnForm SDK] Invalid form slug, URL or baseUrl:', e.message)
+ return null
+ }
+
const iframe = document.createElement('iframe')
iframe.id = slug
iframe.style.border = 'none'
iframe.style.width = width
iframe.style.height = height === 'auto' ? '600px' : height
- let url = `/forms/${slug}`
const sdkToken = generateSdkToken()
- const query = new URLSearchParams({
- _sdkToken: sdkToken,
- _sdkParentOrigin: window.location.origin,
- })
+ url.searchParams.set('_sdkToken', sdkToken)
+ url.searchParams.set('_sdkParentOrigin', window.location.origin)
if (darkMode !== undefined) {
- query.set('darkMode', String(darkMode))
+ url.searchParams.set('darkMode', String(darkMode))
}
- url += `?${query.toString()}`
- iframe.src = url
+ iframe.src = url.toString()
containerEl.appendChild(iframe)
diff --git a/client/public/widgets/opnform-sdk.min.js b/client/public/widgets/opnform-sdk.min.js
index ec2ddb200..d26a8e7ee 100644
--- a/client/public/widgets/opnform-sdk.min.js
+++ b/client/public/widgets/opnform-sdk.min.js
@@ -1,677 +1,9 @@
/* eslint-disable */
-/**
+"use strict";/*!
* OpnForm JavaScript SDK
* Enables programmatic interaction with embedded OpnForm forms
* Includes iFrame Resizer for automatic height adjustment
* @version 1.0.0
- */
-
-// ============================================================================
-// iFrame Resizer v4.3.2 - (c) 2021 David J. Bradshaw - MIT License
-// https://github.com/davidjbradshaw/iframe-resizer
-// ============================================================================
-!function(e){var n,i,t,o,r,a,s,l,f,c,d,u,m,g;function h(){return window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver}function p(e,n,i){e.addEventListener(n,i,!1)}function b(e,n,i){e.removeEventListener(n,i,!1)}function y(e){return c[e]?c[e].log:i}function v(e,n){_("log",e,n,y(e))}function $(e,n){_("info",e,n,y(e))}function w(e,n){_("warn",e,n,!0)}function _(e,n,i,t){var o,a;!0===t&&"object"==typeof window.console&&console[e](r+"["+(a="Host page: "+(o=n),a=window.top!==window.self?window.parentIFrame&&window.parentIFrame.getId?window.parentIFrame.getId()+": "+o:"Nested host page: "+o:a)+"]",i)}function x(e){function n(){i("Height"),i("Width"),O(function(){E(j),I(L),h("onResized",j)},j,"init")}function i(e){var n=Number(c[L]["max"+e]),i=Number(c[L]["min"+e]),e=e.toLowerCase(),t=Number(j[e]);v(L,"Checking "+e+" is in range "+i+"-"+n),t<i&&(t=i,v(L,"Set "+e+" to min value")),n<t&&(t=n,v(L,"Set "+e+" to max value")),j[e]=""+t}function t(e){return P.slice(P.indexOf(":")+o+e)}function l(e,n){var i,t,o;i=function(){var i,t;T("Send Page Info","pageInfo:"+(i=document.body.getBoundingClientRect(),JSON.stringify({iframeHeight:(t=j.iframe.getBoundingClientRect()).height,iframeWidth:t.width,clientHeight:Math.max(document.documentElement.clientHeight,window.innerHeight||0),clientWidth:Math.max(document.documentElement.clientWidth,window.innerWidth||0),offsetTop:parseInt(t.top-i.top,10),offsetLeft:parseInt(t.left-i.left,10),scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,documentHeight:document.documentElement.clientHeight,documentWidth:document.documentElement.clientWidth,windowHeight:window.innerHeight,windowWidth:window.innerWidth})),e,n)},t=32,m[o=n]||(m[o]=setTimeout(function(){m[o]=null,i()},t))}function f(e){return e=e.getBoundingClientRect(),M(L),{x:Math.floor(Number(e.left)+Number(s.x)),y:Math.floor(Number(e.top)+Number(s.y))}}function d(e){var n=e?f(j.iframe):{x:0,y:0},i={x:Number(j.width)+n.x,y:Number(j.height)+n.y};v(L,"Reposition requested from iFrame (offset x:"+n.x+" y:"+n.y+")"),window.top===window.self?(s=i,u(),v(L,"--")):window.parentIFrame?window.parentIFrame["scrollTo"+(e?"Offset":"")](i.x,i.y):w(L,"Unable to scroll to requested position, window.parentIFrame not found")}function u(){!1===h("onScroll",s)?R():I(L)}function g(e){var n,i={};i=0===Number(j.width)&&0===Number(j.height)?{x:(n=t(9).split(":"))[1],y:n[0]}:{x:j.width,y:j.height},h(e,{iframe:j.iframe,screenX:Number(i.x),screenY:Number(i.y),type:j.type})}function h(e,n){return k(L,e,n)}var y,_,x,z,H,S,P=e.data,j={},L=null;if("[iFrameResizerChild]Ready"===P)for(var A in c)T("iFrame requested init",C(A),c[A].iframe,A);else r===(""+P).slice(0,a)&&P.slice(a).split(":")[0]in c?(c[L=(j=(_=(y=P.slice(a).split(":"))[1]?parseInt(y[1],10):0,z=getComputedStyle(x=c[y[0]]&&c[y[0]].iframe),{iframe:x,id:y[0],height:_+function(e){if("border-box"!==e.boxSizing)return 0;var n=e.paddingTop?parseInt(e.paddingTop,10):0,e=e.paddingBottom?parseInt(e.paddingBottom,10):0;return n+e}(z)+function(e){if("border-box"!==e.boxSizing)return 0;var n=e.borderTopWidth?parseInt(e.borderTopWidth,10):0,e=e.borderBottomWidth?parseInt(e.borderBottomWidth,10):0;return n+e}(z),width:y[2],type:y[3]})).id]&&(c[L].loaded=!0),(S=j.type in{true:1,false:1,undefined:1})&&v(L,"Ignoring init message from meta parent page"),!S&&(S=!0,c[H=L]||(S=!1,w(j.type+" No settings for "+H+". Message was: "+P)),S)&&(v(L,"Received: "+P),H=!0,null===j.iframe&&(w(L,"IFrame ("+j.id+") not found"),H=!1),H&&function n(){var i=e.origin,t=c[L]&&c[L].checkOrigin;if(t&&""+i!="null"&&!function(){if(t.constructor!==Array)return e=c[L]&&c[L].remoteHost,v(L,"Checking connection is from: "+e),i===e;var e,n=0,o=!1;for(v(L,"Checking connection is from allowed list of origins: "+t);n<t.length;n++)if(t[n]===i){o=!0;break}return o}())throw Error("Unexpected message received from: "+i+" for "+j.iframe.id+". Message was: "+e.data+". This error can be disabled by setting the checkOrigin: false option or by providing of array of trusted domains.");return 1}()&&function e(){var i,o,r,a,m;switch(c[L]&&c[L].firstRun&&c[L]&&(c[L].firstRun=!1),j.type){case"close":F(j.iframe);break;case"message":o=t(6),v(L,"onMessage passed: {iframe: "+j.iframe.id+", message: "+o+"}"),h("onMessage",{iframe:j.iframe,message:JSON.parse(o)}),v(L,"--");break;case"mouseenter":g("onMouseEnter");break;case"mouseleave":g("onMouseLeave");break;case"autoResize":c[L].autoResize=JSON.parse(t(9));break;case"scrollTo":d(!1);break;case"scrollToOffset":d(!0);break;case"pageInfo":l(c[L]&&c[L].iframe,L),i=L,y("Add ",p),c[i]&&(c[i].stopPageInfo=$);break;case"pageInfoStop":c[L]&&c[L].stopPageInfo&&(c[L].stopPageInfo(),delete c[L].stopPageInfo);break;case"inPageLink":t(9),m=decodeURIComponent(a=a.split("#")[1]||""),(m=document.getElementById(m)||document.getElementsByName(m)[0])?(m=f(m),v(L,"Moving to in page link (#"+a+") at x: "+m.x+" y: "+m.y),s={x:m.x,y:m.y},u(),v(L,"--")):window.top===window.self?v(L,"In page link #"+a+" not found"):window.parentIFrame?window.parentIFrame.moveToAnchor(a):v(L,"In page link #"+a+" not found and window.parentIFrame not found");break;case"reset":W(j);break;case"init":n(),h("onInit",j.iframe);break;default:0===Number(j.width)&&0===Number(j.height)?w("Unsupported message received ("+j.type+"), this is likely due to the iframe containing a later version of iframe-resizer than the parent page"):n()}function y(e,n){function t(){c[i]?l(c[i].iframe,i):$()}["scroll","resize"].forEach(function(o){v(i,e+o+" listener for sendPageInfo"),n(window,o,t)})}function $(){y("Remove ",b)}}())):$(L,"Ignored: "+P)}function k(e,n,i){var t=null,o=null;if(c[e]){if("function"!=typeof(t=c[e][n]))throw TypeError(n+" on iFrame["+e+"] is not a function");o=t(i)}return o}function z(e){delete c[e=e.id]}function F(e){var n=e.id;if(!1===k(n,"onClose",n))v(n,"Close iframe cancelled by onClose event");else{v(n,"Removing iFrame: "+n);try{e.parentNode&&e.parentNode.removeChild(e)}catch(i){w(i)}k(n,"onClosed",n),v(n,"--"),z(e)}}function M(n){null===s&&v(n,"Get page position: "+(s={x:window.pageXOffset===e?document.documentElement.scrollLeft:window.pageXOffset,y:window.pageYOffset===e?document.documentElement.scrollTop:window.pageYOffset}).x+","+s.y)}function I(e){null!==s&&(window.scrollTo(s.x,s.y),v(e,"Set page position: "+s.x+","+s.y),R())}function R(){s=null}function W(e){v(e.id,"Size reset requested by "+("init"===e.type?"host page":"iFrame")),M(e.id),O(function(){E(e),T("reset","reset",e.iframe,e.id)},e,"reset")}function E(e){function n(n){var o;o=n,e.id?(e.iframe.style[o]=e[o]+"px",v(e.id,"IFrame ("+i+") "+o+" set to "+e[o]+"px")):v("undefined","messageData id not set"),function n(o){var r;function a(){Object.keys(c).forEach(function(e){var n;function i(e){return"0px"===(c[n]&&c[n].iframe.style[e])}c[n=e]&&null!==c[n].iframe.offsetParent&&(i("height")||i("width"))&&T("Visibility change","resize",c[n].iframe,n)})}!t&&"0"===e[o]&&(t=!0,v(i,"Hidden iFrame detected, creating visibility listener"),o=h())&&(r=document.querySelector("body"),new o(function e(n){v("window","Mutation observed: "+n[0].target+" "+n[0].type),S(a,16)}).observe(r,{attributes:!0,attributeOldValue:!1,characterData:!0,characterDataOldValue:!1,childList:!0,subtree:!0}))}(n)}var i=e.iframe.id;c[i]&&(c[i].sizeHeight&&n("height"),c[i].sizeWidth)&&n("width")}function O(e,n,i){i!==n.type&&l&&!window.jasmine?(v(n.id,"Requesting animation frame"),l(e)):e()}function T(e,n,i,t,o){var a,s=!1;c[t=t||i.id]&&(i&&"contentWindow"in i&&null!==i.contentWindow?(a=c[t]&&c[t].targetOrigin,v(t,"["+e+"] Sending msg to iframe["+t+"] ("+n+") targetOrigin: "+a),i.contentWindow.postMessage(r+n,a)):w(t,"["+e+"] IFrame("+t+") not found"),o&&c[t]&&c[t].warningTimeout&&(c[t].msgTimeout=setTimeout(function(){!c[t]||c[t].loaded||s||(s=!0,w(t,"IFrame has not responded within "+c[t].warningTimeout/1e3+" seconds. Check iFrameResizer.contentWindow.js has been loaded in iFrame. This message can be ignored if everything is working, or you can set the warningTimeout option to a higher value or zero to suppress this warning."))},c[t].warningTimeout)))}function C(e){return e+":"+c[e].bodyMarginV1+":"+c[e].sizeWidth+":"+c[e].log+":"+c[e].interval+":"+c[e].enablePublicMethods+":"+c[e].autoResize+":"+c[e].bodyMargin+":"+c[e].heightCalculationMethod+":"+c[e].bodyBackground+":"+c[e].bodyPadding+":"+c[e].tolerance+":"+c[e].inPageLinks+":"+c[e].resizeFrom+":"+c[e].widthCalculationMethod+":"+c[e].mouseEvents}function H(t,o){function r(e){var n=e.split("Callback");2===n.length&&(this[n="on"+n[0].charAt(0).toUpperCase()+n[0].slice(1)]=this[e],delete this[e],w(l,"Deprecated: '"+e+"' has been renamed '"+n+"'. The old method will be removed in the next major version."))}var a,s,l=function(e){var r;if("string"!=typeof e)throw TypeError("Invaild id for iFrame. Expected String");return""===e&&(t.id=(r=o&&o.id||u.id+n++,null!==document.getElementById(r)&&(r+=n++),e=r),i=(o||{}).log,v(e,"Added missing iframe ID: "+e+" ("+t.src+")")),e}(t.id);if(l in c&&"iFrameResizer"in t)w(l,"Ignored iFrame, already setup.");else{switch(function e(n){if(n=n||{},c[l]=Object.create(null),c[l].iframe=t,c[l].firstRun=!0,c[l].remoteHost=t.src&&t.src.split("/").slice(0,3).join("/"),"object"!=typeof n)throw TypeError("Options is not an object");Object.keys(n).forEach(r,n);var i,o=n;for(i in u)Object.prototype.hasOwnProperty.call(u,i)&&(c[l][i]=(Object.prototype.hasOwnProperty.call(o,i)?o:u)[i]);c[l]&&(c[l].targetOrigin=!0!==c[l].checkOrigin||""===(n=c[l].remoteHost)||null!==n.match(/^(about:blank|javascript:|file:\/\/)/)?'*':n)}(o),v(l,"IFrame scrolling "+(c[l]&&c[l].scrolling?"enabled":"disabled")+" for "+l),t.style.overflow=!1===(c[l]&&c[l].scrolling)?"hidden":"auto",c[l]&&c[l].scrolling){case"omit":break;case!0:t.scrolling="yes";break;case!1:t.scrolling="no";break;default:t.scrolling=c[l]?c[l].scrolling:"no"}m("Height"),m("Width"),d("maxHeight"),d("minHeight"),d("maxWidth"),d("minWidth"),"number"!=typeof(c[l]&&c[l].bodyMargin)&&"0"!==(c[l]&&c[l].bodyMargin)||(c[l].bodyMarginV1=c[l].bodyMargin,c[l].bodyMargin=c[l].bodyMargin+"px"),a=C(l),(s=h())&&t.parentNode&&new s(function(e){e.forEach(function(e){Array.prototype.slice.call(e.removedNodes).forEach(function(e){e===t&&F(t)})})}).observe(t.parentNode,{childList:!0}),p(t,"load",function(){var n,i;T("iFrame.onload",a,t,e,!0),n=c[l]&&c[l].firstRun,i=c[l]&&c[l].heightCalculationMethod in f,!n&&i&&W({iframe:t,height:0,width:0,type:"init"})}),T("init",a,t,e,!0),c[l]&&(c[l].iframe.iFrameResizer={close:F.bind(null,c[l].iframe),removeListeners:z.bind(null,c[l].iframe),resize:T.bind(null,"Window resize","resize",c[l].iframe),moveToAnchor:function(e){T("Move to anchor","moveToAnchor:"+e,c[l].iframe,l)},sendMessage:function(e){T("Send Message","message:"+(e=JSON.stringify(e)),c[l].iframe,l)}})}function d(e){var n=c[l][e];1/0!==n&&0!==n&&(t.style[e]="number"==typeof n?n+"px":n,v(l,"Set "+e+" = "+t.style[e]))}function m(e){if(c[l]["min"+e]>c[l]["max"+e])throw Error("Value for min"+e+" can not be greater than max"+e)}}function S(e,n){null===d&&(d=setTimeout(function(){d=null,e()},n))}function P(){"hidden"!==document.visibilityState&&(v("document","Trigger event: Visibility change"),S(function(){j("Tab Visible","resize")},16))}function j(e,n){Object.keys(c).forEach(function(i){var t;c[t=i]&&"parent"===c[t].resizeFrom&&c[t].autoResize&&!c[t].firstRun&&T(e,n,c[i].iframe,i)})}function L(){function n(e,n){if(n){if(!n.tagName)throw TypeError("Object is not a valid DOM element");if("IFRAME"!==n.tagName.toUpperCase())throw TypeError("Expected <IFRAME> tag, found <"+n.tagName+">");H(n,e),i.push(n)}}for(var i,t=["moz","webkit","o","ms"],o=0;o<t.length&&!l;o+=1)l=window[t[o]+"RequestAnimationFrame"];return l?l=l.bind(window):v("setup","RequestAnimationFrame not supported"),p(window,"message",x),p(window,"resize",function(){var e;v("window","Trigger event: "+(e="resize")),S(function(){j("Window "+e,"resize")},16)}),p(document,"visibilitychange",P),p(document,"-webkit-visibilitychange",P),function(t,o){var r;switch(i=[],(r=t)&&r.enablePublicMethods&&w("enablePublicMethods option has been removed, public methods are now always available in the iFrame"),typeof o){case"undefined":case"string":Array.prototype.forEach.call(document.querySelectorAll(o||"iframe"),n.bind(e,t));break;case"object":n(t,o);break;default:throw TypeError("Unexpected data type ("+typeof o+")")}return i}}"undefined"!=typeof window&&(n=0,t=i=!1,o=7,a=(r="[iFrameSizer]").length,s=null,l=window.requestAnimationFrame,f=Object.freeze({max:1,scroll:1,bodyScroll:1,documentElementScroll:1}),c={},d=null,u=Object.freeze({autoResize:!0,bodyBackground:null,bodyMargin:null,bodyMarginV1:8,bodyPadding:null,checkOrigin:!0,inPageLinks:!1,enablePublicMethods:!0,heightCalculationMethod:"bodyOffset",id:"iFrameResizer",interval:32,log:!1,maxHeight:1/0,maxWidth:1/0,minHeight:0,minWidth:0,mouseEvents:!0,resizeFrom:"parent",scrolling:!1,sizeHeight:!0,sizeWidth:!1,warningTimeout:5e3,tolerance:0,widthCalculationMethod:"scroll",onClose:function(){return!0},onClosed:function(){},onInit:function(){},onMessage:function(){w("onMessage function not defined")},onMouseEnter:function(){},onMouseLeave:function(){},onResized:function(){},onScroll:function(){return!0}}),m={},window.jQuery!==e&&((g=window.jQuery).fn?g.fn.iFrameResize||(g.fn.iFrameResize=function(e){return this.filter("iframe").each(function(n,i){H(i,e)}).end()}):$("","Unable to bind to jQuery, it is not fully loaded.")),"function"==typeof define&&define.amd?define([],L):"object"==typeof module&&"object"==typeof module.exports&&(module.exports=L()),window.iFrameResize=window.iFrameResize||L())}();
-
-// ============================================================================
-// OpnForm SDK
-// ============================================================================
-(function (global) {
- 'use strict'
-
- // Message protocol prefix
- const MSG_PREFIX = 'opnform:'
-
- const ATTRIBUTION_PARAMETERS = [
- 'utm_source', 'utm_medium', 'utm_campaign', 'utm_id', 'utm_term', 'utm_content',
- 'utm_source_platform', 'utm_creative_format', 'utm_marketing_tactic',
- 'gclid', 'gbraid', 'wbraid', 'dclid', 'fbclid', 'ttclid', 'msclkid'
- ]
- const ATTRIBUTION_MAX_VALUE_LENGTH = 2048
-
- function getPageAttribution() {
- const params = new URLSearchParams(window.location.search)
- return ATTRIBUTION_PARAMETERS.reduce((attribution, parameter) => {
- const value = params.getAll(parameter).find(candidate => (
- candidate.trim() !== '' && candidate.length <= ATTRIBUTION_MAX_VALUE_LENGTH
- ))
- if (value !== undefined) attribution[parameter] = value
- return attribution
- }, {})
- }
-
- // Event types
- const EVENTS = {
- READY: 'ready',
- SUBMIT: 'submit',
- SUBMIT_START: 'submitStart',
- SUBMIT_ERROR: 'submitError',
- RESET: 'reset',
- PAGE_CHANGE: 'pageChange',
- NEXT_PAGE: 'nextPage',
- PREVIOUS_PAGE: 'previousPage',
- DATA_CHANGE: 'dataChange',
- ERROR: 'error',
- SHOW: 'show',
- HIDE: 'hide',
- RESIZE: 'resize'
- }
-
- function generateSdkToken() {
- if (global.crypto?.randomUUID) {
- return global.crypto.randomUUID()
- }
- return `${Date.now()}-${Math.random().toString(36).slice(2)}`
- }
-
- function getIframeOrigin(iframe) {
- try {
- if (!iframe?.src) return null
- return new URL(iframe.src, window.location.href).origin
- } catch (e) {
- return null
- }
- }
-
- function getIframeSdkToken(iframe) {
- try {
- if (!iframe?.src) return null
- return new URL(iframe.src, window.location.href).searchParams.get('_sdkToken')
- } catch (e) {
- return null
- }
- }
-
- /**
- * Simple EventEmitter implementation
- */
- class EventEmitter {
- constructor() {
- this._listeners = {}
- this._onceListeners = {}
- }
-
- on(event, callback) {
- if (Array.isArray(event)) {
- event.forEach(e => this.on(e, callback))
- return this
- }
- if (!this._listeners[event]) {
- this._listeners[event] = []
- }
- this._listeners[event].push(callback)
- return this
- }
-
- once(event, callback) {
- if (!this._onceListeners[event]) {
- this._onceListeners[event] = []
- }
- this._onceListeners[event].push(callback)
- return this
- }
-
- off(event, callback) {
- if (!callback) {
- delete this._listeners[event]
- delete this._onceListeners[event]
- return this
- }
- if (this._listeners[event]) {
- this._listeners[event] = this._listeners[event].filter(cb => cb !== callback)
- }
- if (this._onceListeners[event]) {
- this._onceListeners[event] = this._onceListeners[event].filter(cb => cb !== callback)
- }
- return this
- }
-
- emit(event, data) {
- if (this._listeners[event]) {
- this._listeners[event].forEach(callback => {
- try { callback(data) } catch (e) { console.error('[OpnForm SDK] Error in event handler:', e) }
- })
- }
- if (this._onceListeners[event]) {
- const callbacks = this._onceListeners[event]
- delete this._onceListeners[event]
- callbacks.forEach(callback => {
- try { callback(data) } catch (e) { console.error('[OpnForm SDK] Error in once handler:', e) }
- })
- }
- }
- }
-
- /**
- * Form Instance - represents a single embedded form
- */
- class FormInstance extends EventEmitter {
- constructor(iframe, slug, sdk, sdkToken = null) {
- super()
- this.iframe = iframe
- this.slug = slug
- this.id = iframe.id || slug
- this._sdk = sdk
- this._sdkToken = sdkToken || getIframeSdkToken(iframe) || generateSdkToken()
- this._ready = false
- this._pendingRequests = {}
- this._requestId = 0
- this._cachedData = {}
- this._cachedErrors = {}
- this._darkMode = false
- this._currentPage = { index: 0, total: 1 }
- this._popupOpen = false
- this._resizeInitialized = false
- this._targetOrigin = getIframeOrigin(iframe) || '*'
- this._handshakeComplete = false
- this._handshakePromise = null
- this._handshakeResolve = null
- this._handshakeReject = null
- this._handshakeRetryTimer = null
- }
-
- isReady() { return this._ready }
-
- _sendHandshake() {
- if (!this.iframe?.contentWindow || !this._sdkToken) return
-
- this.iframe.contentWindow.postMessage({
- type: MSG_PREFIX + 'handshake',
- formSlug: this.slug,
- _sdkToken: this._sdkToken,
- parentOrigin: window.location.origin,
- trackingParameters: getPageAttribution(),
- }, this._targetOrigin)
- }
-
- _createHandshakePromise() {
- return new Promise((resolve, reject) => {
- this._handshakeResolve = resolve
- this._handshakeReject = reject
- this._sendHandshake()
-
- this._handshakeRetryTimer = setInterval(() => {
- if (this._handshakeComplete) return
- this._sendHandshake()
- }, 250)
-
- setTimeout(() => {
- if (this._handshakeComplete) return
-
- if (this._handshakeRetryTimer) {
- clearInterval(this._handshakeRetryTimer)
- this._handshakeRetryTimer = null
- }
-
- this._handshakePromise = null
- this._handshakeResolve = null
- if (this._handshakeReject) {
- this._handshakeReject(new Error('SDK handshake timeout'))
- this._handshakeReject = null
- }
- }, 3000)
- })
- }
-
- _startHandshake() {
- this._handshakePromise = this._createHandshakePromise()
- this._handshakePromise.catch(() => {})
-
- if (this.iframe.contentWindow) {
- this._sendHandshake()
- } else {
- this.iframe.addEventListener('load', () => this._sendHandshake())
- }
- }
-
- _ensureHandshake() {
- if (this._handshakeComplete) {
- return Promise.resolve()
- }
-
- if (!this._handshakePromise) {
- this._handshakePromise = this._createHandshakePromise()
- }
-
- return this._handshakePromise
- }
-
- _handleHandshakeAck(message) {
- if (this._handshakeRetryTimer) {
- clearInterval(this._handshakeRetryTimer)
- this._handshakeRetryTimer = null
- }
-
- if (message.success === false) {
- this._handshakePromise = null
- this._handshakeResolve = null
- if (this._handshakeReject) {
- this._handshakeReject(new Error('SDK handshake rejected'))
- this._handshakeReject = null
- }
- return
- }
-
- this._handshakeComplete = true
-
- if (this._handshakeResolve) {
- this._handshakeResolve()
- this._handshakeResolve = null
- this._handshakeReject = null
- }
- }
-
- _sendCommand(command, payload = {}) {
- if (!this.iframe || !this.iframe.contentWindow) {
- console.warn('[OpnForm SDK] Cannot send command - iframe not available')
- return Promise.reject(new Error('Iframe not available'))
- }
-
- return this._ensureHandshake().then(() => {
- const requestId = ++this._requestId
- const message = {
- type: MSG_PREFIX + 'command',
- command: command,
- formSlug: this.slug,
- requestId: requestId,
- payload: payload,
- _sdkToken: this._sdkToken,
- }
-
- return new Promise((resolve, reject) => {
- this._pendingRequests[requestId] = { resolve, reject }
- setTimeout(() => {
- if (this._pendingRequests[requestId]) {
- delete this._pendingRequests[requestId]
- reject(new Error('Command timeout'))
- }
- }, 5000)
- this.iframe.contentWindow.postMessage(message, this._targetOrigin)
- })
- })
- }
-
- matchesMessageSource(event) {
- if (!this.iframe || event.source !== this.iframe.contentWindow) return false
- return this._targetOrigin === '*' || event.origin === this._targetOrigin
- }
-
- _handleResponse(response) {
- const pending = this._pendingRequests[response.requestId]
- if (pending) {
- delete this._pendingRequests[response.requestId]
- if (response.success) {
- pending.resolve(response.data)
- } else {
- pending.reject(new Error(response.error || 'Command failed'))
- }
- }
- }
-
- // --- Field Operations ---
- getField(fieldId) { return this._cachedData[fieldId] }
- setField(fieldId, value) { return this._sendCommand('setField', { fieldId, value }) }
- setFields(data) { return this._sendCommand('setFields', { data }) }
- getData() { return { ...this._cachedData } }
- clearField(fieldId) { return this._sendCommand('clearField', { fieldId }) }
- clearAll() { return this._sendCommand('clearAll', {}) }
-
- // --- Field State ---
- hasError(fieldId) { return !!this._cachedErrors[fieldId] }
- getError(fieldId) { return this._cachedErrors[fieldId] || null }
- getErrors() { return { ...this._cachedErrors } }
- isFieldVisible(fieldId) { return this._sendCommand('isFieldVisible', { fieldId }) }
-
- // --- Theme ---
- toggleDarkMode() { return this.setDarkMode(!this._darkMode) }
- setDarkMode(enabled) {
- this._darkMode = enabled === 'auto' ? null : !!enabled
- return this._sendCommand('setDarkMode', { enabled })
- }
- isDarkMode() { return this._darkMode }
- setTheme(theme) { return this._sendCommand('setTheme', { theme }) }
-
- // --- Navigation ---
- goToPage(index) { return this._sendCommand('goToPage', { index }) }
- nextPage() { return this._sendCommand('nextPage', {}) }
- previousPage() { return this._sendCommand('previousPage', {}) }
- getCurrentPage() { return { ...this._currentPage } }
- canGoNext() { return this._currentPage.index < this._currentPage.total - 1 }
- canGoPrevious() { return this._currentPage.index > 0 }
-
- // --- Actions ---
- submit() { return this._sendCommand('submit', {}) }
- reset() { return this._sendCommand('reset', {}) }
- focusFirstError() { return this._sendCommand('focusFirstError', {}) }
-
- // --- Popup Control ---
- open() {
- const mainDiv = document.querySelector('.nf-main')
- if (mainDiv) {
- mainDiv.classList.add('open')
- this._popupOpen = true
- this.emit(EVENTS.SHOW, { form: this._getFormInfo() })
- }
- }
-
- close() {
- const mainDiv = document.querySelector('.nf-main')
- if (mainDiv) {
- mainDiv.classList.remove('open')
- this._popupOpen = false
- this.emit(EVENTS.HIDE, { form: this._getFormInfo() })
- }
- }
-
- toggle() {
- if (this._popupOpen) { this.close() } else { this.open() }
- }
-
- isOpen() { return this._popupOpen }
-
- _getFormInfo() {
- return { slug: this.slug, id: this.id }
- }
-
- /**
- * Initialize auto-resize for this form's iframe
- */
- initResize() {
- if (this._resizeInitialized) return
- if (global.iFrameResize && this.iframe) {
- global.iFrameResize({ log: false }, this.iframe)
- this._resizeInitialized = true
- }
- }
- }
-
- /**
- * Main OpnForm SDK
- */
- class OpnFormSDK extends EventEmitter {
- constructor() {
- super()
- this._forms = {}
- this._options = {
- autoResize: true,
- defaultDarkMode: 'auto',
- preventRedirect: false
- }
- this._initialized = false
- this._messageHandler = this._handleMessage.bind(this)
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => this._autoInit())
- } else {
- this._autoInit()
- }
- }
-
- init(options = {}) {
- this._options = { ...this._options, ...options }
-
- if (!this._initialized) {
- window.addEventListener('message', this._messageHandler)
- this._initialized = true
- }
-
- this._discoverForms()
-
- if (this._options.onReady && Object.keys(this._forms).length > 0) {
- const readyForms = Object.values(this._forms).filter(f => f.isReady())
- if (readyForms.length > 0) {
- this._options.onReady(readyForms)
- }
- }
- }
-
- _autoInit() {
- window.addEventListener('message', this._messageHandler)
- this._initialized = true
- this._discoverForms()
- }
-
- _discoverForms() {
- const iframes = document.querySelectorAll('iframe')
- iframes.forEach(iframe => {
- const src = iframe.src || ''
- if (src.includes('/forms/') && !this._forms[iframe.id]) {
- const slugMatch = src.match(/\/forms\/([^/?#]+)/)
- const slug = slugMatch ? slugMatch[1] : iframe.id
- if (slug) {
- this._registerForm(iframe, slug)
- }
- }
- })
- }
-
- _registerForm(iframe, slug, sdkToken = null) {
- const instance = new FormInstance(iframe, slug, this, sdkToken)
- this._forms[slug] = instance
-
- if (iframe.id && iframe.id !== slug) {
- this._forms[iframe.id] = instance
- }
-
- instance._startHandshake()
-
- // Auto-initialize resize if enabled
- if (this._options.autoResize !== false) {
- // Wait for iframe to be ready
- if (iframe.contentWindow) {
- instance.initResize()
- } else {
- iframe.addEventListener('load', () => instance.initResize())
- }
- }
-
- return instance
- }
-
- _handleMessage(event) {
- const data = event.data
- if (!data || typeof data !== 'object') return
-
- // Handle legacy form-submitted event
- if (data.type === 'form-submitted') {
- const form = this._forms[data.form?.slug]
- if (form?.matchesMessageSource(event)) {
- this._handleLegacySubmit(data, form)
- }
- return
- }
-
- // Handle SDK events
- if (data.type && data.type.startsWith && data.type.startsWith(MSG_PREFIX)) {
- const form = this._forms[data.formSlug]
- if (!form?.matchesMessageSource(event)) return
-
- const messageType = data.type.replace(MSG_PREFIX, '')
- if (messageType === 'event') {
- this._handleEvent(data, form)
- } else if (messageType === 'response') {
- this._handleResponse(data, form)
- } else if (messageType === 'handshake-ack') {
- form._handleHandshakeAck(data)
- }
- }
- }
-
- _handleLegacySubmit(data, form = null) {
- const formSlug = data.form?.slug
- form = form || this._forms[formSlug]
-
- const eventData = {
- form: { slug: formSlug, id: data.form?.id },
- data: data.submission_data || {},
- submissionId: data.submission_id,
- completionTime: data.completion_time
- }
-
- if (form) {
- form._cachedData = eventData.data
- form.emit(EVENTS.SUBMIT, eventData)
- }
-
- this.emit(EVENTS.SUBMIT, eventData)
-
- if (!this._options.preventRedirect && data.form?.redirect_target_url) {
- window.top.location.href = data.form.redirect_target_url
- }
- }
-
- _handleEvent(message, form = null) {
- const { event, formSlug, payload } = message
- form = form || this._forms[formSlug]
-
- if (!form) return
-
- switch (event) {
- case EVENTS.READY:
- form._ready = true
- if (payload.data) form._cachedData = payload.data
- if (payload.currentPage) form._currentPage = payload.currentPage
- if (payload.darkMode !== undefined) form._darkMode = payload.darkMode
- break
- case EVENTS.DATA_CHANGE:
- form._cachedData = payload.data || {}
- break
- case EVENTS.ERROR:
- form._cachedErrors = payload.errors || {}
- break
- case EVENTS.SUBMIT:
- form._cachedData = payload.data || {}
- break
- case EVENTS.SUBMIT_ERROR:
- form._cachedErrors = payload.errors || {}
- break
- case EVENTS.PAGE_CHANGE:
- case EVENTS.NEXT_PAGE:
- case EVENTS.PREVIOUS_PAGE:
- if (payload.currentPage !== undefined) form._currentPage.index = payload.currentPage
- if (payload.toPage !== undefined) form._currentPage.index = payload.toPage
- if (payload.totalPages !== undefined) form._currentPage.total = payload.totalPages
- break
- case EVENTS.RESET:
- form._cachedData = {}
- form._cachedErrors = {}
- form._currentPage = { index: 0, total: form._currentPage.total }
- break
- }
-
- const eventData = { form: form._getFormInfo(), ...payload }
- form.emit(event, eventData)
- this.emit(event, eventData)
-
- if (event === EVENTS.READY && this._options.onReady) {
- const allForms = Object.values(this._forms)
- const uniqueForms = [...new Set(allForms)]
- if (uniqueForms.every(f => f.isReady())) {
- this._options.onReady(uniqueForms)
- }
- }
- }
-
- _handleResponse(message, form = null) {
- const { formSlug, requestId, success, data, error } = message
- form = form || this._forms[formSlug]
- if (form) {
- form._handleResponse({ requestId, success, data, error })
- }
- }
-
- get(slugOrId) { return this._forms[slugOrId] || null }
-
- getAll() {
- const instances = Object.values(this._forms)
- return [...new Set(instances)]
- }
-
- isReady(slugOrId) {
- const form = this._forms[slugOrId]
- return form ? form.isReady() : false
- }
-
- create(slug, options = {}) {
- const { container, width = '100%', height = 'auto', darkMode, onSubmit } = options
-
- let containerEl = container
- if (typeof container === 'string') {
- containerEl = document.querySelector(container)
- }
-
- if (!containerEl) {
- console.error('[OpnForm SDK] Container element not found')
- return null
- }
-
- const iframe = document.createElement('iframe')
- iframe.id = slug
- iframe.style.border = 'none'
- iframe.style.width = width
- iframe.style.height = height === 'auto' ? '600px' : height
-
- let url = `/forms/${slug}`
- const sdkToken = generateSdkToken()
- const query = new URLSearchParams({
- _sdkToken: sdkToken,
- _sdkParentOrigin: window.location.origin,
- })
- if (darkMode !== undefined) {
- query.set('darkMode', String(darkMode))
- }
- url += `?${query.toString()}`
- iframe.src = url
-
- containerEl.appendChild(iframe)
-
- const form = this._registerForm(iframe, slug, sdkToken)
-
- if (onSubmit) {
- form.on(EVENTS.SUBMIT, onSubmit)
- }
-
- return form
- }
-
- /**
- * Initialize auto-resize for a specific form
- */
- initAutoResize(slugOrId) {
- const form = this._forms[slugOrId]
- if (form) {
- form.initResize()
- } else if (global.iFrameResize) {
- const selector = '#' + slugOrId
- global.iFrameResize({ log: false }, selector)
- }
- }
- }
-
- // Create singleton instance
- const opnform = new OpnFormSDK()
-
- // Expose to global scope
- global.opnform = opnform
-
- // Backward compatibility with initEmbed
- if (!global.initEmbed) {
- global.initEmbed = function(formSlug, options = {}) {
- opnform.init(options)
-
- const form = opnform.get(formSlug)
- if (form) {
- form.on('submit', (data) => {
- if (data.form?.redirect_target_url) {
- window.top.location.href = data.form.redirect_target_url
- }
- })
- }
-
- // Auto-resize is now handled automatically by the SDK
- if (options.autoResize !== false) {
- opnform.initAutoResize(formSlug)
- }
- }
- }
-
-})(typeof window !== 'undefined' ? window : this)
+ *//*! iFrame Resizer v4.3.2 - (c) 2021 David J. Bradshaw - MIT License
+ * https://github.com/davidjbradshaw/iframe-resizer
+ */(function(F){var D,K,Z,ee,b,W,E,S,X,t,G,z,R,e;function n(){return window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver}function s(i,o,l){i.addEventListener(o,l,!1)}function f(i,o,l){i.removeEventListener(o,l,!1)}function p(i){return t[i]?t[i].log:K}function a(i,o){A("log",i,o,p(i))}function C(i,o){A("info",i,o,p(i))}function v(i,o){A("warn",i,o,!0)}function A(i,o,l,c){var w,r;c===!0&&typeof window.console=="object"&&console[i](b+"["+(r="Host page: "+(w=o),r=window.top!==window.self?window.parentIFrame&&window.parentIFrame.getId?window.parentIFrame.getId()+": "+w:"Nested host page: "+w:r)+"]",l)}function H(i){function o(){l("Height"),l("Width"),de(function(){ae(_),q(d),h("onResized",_)},_,"init")}function l(M){var g=Number(t[d]["max"+M]),u=Number(t[d]["min"+M]),M=M.toLowerCase(),k=Number(_[M]);a(d,"Checking "+M+" is in range "+u+"-"+g),k<u&&(k=u,a(d,"Set "+M+" to min value")),g<k&&(k=g,a(d,"Set "+M+" to max value")),_[M]=""+k}function c(T){return L.slice(L.indexOf(":")+ee+T)}function w(T,g){var u,M,k;u=function(){var P,B;x("Send Page Info","pageInfo:"+(P=document.body.getBoundingClientRect(),JSON.stringify({iframeHeight:(B=_.iframe.getBoundingClientRect()).height,iframeWidth:B.width,clientHeight:Math.max(document.documentElement.clientHeight,window.innerHeight||0),clientWidth:Math.max(document.documentElement.clientWidth,window.innerWidth||0),offsetTop:parseInt(B.top-P.top,10),offsetLeft:parseInt(B.left-P.left,10),scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,documentHeight:document.documentElement.clientHeight,documentWidth:document.documentElement.clientWidth,windowHeight:window.innerHeight,windowWidth:window.innerWidth})),T,g)},M=32,R[k=g]||(R[k]=setTimeout(function(){R[k]=null,u()},M))}function r(T){return T=T.getBoundingClientRect(),$(d),{x:Math.floor(Number(T.left)+Number(E.x)),y:Math.floor(Number(T.top)+Number(E.y))}}function I(T){var g=T?r(_.iframe):{x:0,y:0},u={x:Number(_.width)+g.x,y:Number(_.height)+g.y};a(d,"Reposition requested from iFrame (offset x:"+g.x+" y:"+g.y+")"),window.top===window.self?(E=u,N(),a(d,"--")):window.parentIFrame?window.parentIFrame["scrollTo"+(T?"Offset":"")](u.x,u.y):v(d,"Unable to scroll to requested position, window.parentIFrame not found")}function N(){h("onScroll",E)===!1?Y():q(d)}function m(T){var g,u={};u=Number(_.width)===0&&Number(_.height)===0?{x:(g=c(9).split(":"))[1],y:g[0]}:{x:_.width,y:_.height},h(T,{iframe:_.iframe,screenX:Number(u.x),screenY:Number(u.y),type:_.type})}function h(T,g){return U(d,T,g)}var y,j,te,re,J,Q,L=i.data,_={},d=null;if(L==="[iFrameResizerChild]Ready")for(var se in t)x("iFrame requested init",ce(se),t[se].iframe,se);else b===(""+L).slice(0,W)&&L.slice(W).split(":")[0]in t?(t[d=(_=(j=(y=L.slice(W).split(":"))[1]?parseInt(y[1],10):0,re=getComputedStyle(te=t[y[0]]&&t[y[0]].iframe),{iframe:te,id:y[0],height:j+function(u){if(u.boxSizing!=="border-box")return 0;var g=u.paddingTop?parseInt(u.paddingTop,10):0,u=u.paddingBottom?parseInt(u.paddingBottom,10):0;return g+u}(re)+function(u){if(u.boxSizing!=="border-box")return 0;var g=u.borderTopWidth?parseInt(u.borderTopWidth,10):0,u=u.borderBottomWidth?parseInt(u.borderBottomWidth,10):0;return g+u}(re),width:y[2],type:y[3]})).id]&&(t[d].loaded=!0),(Q=_.type in{true:1,false:1,undefined:1})&&a(d,"Ignoring init message from meta parent page"),!Q&&(Q=!0,t[J=d]||(Q=!1,v(_.type+" No settings for "+J+". Message was: "+L)),Q)&&(a(d,"Received: "+L),J=!0,_.iframe===null&&(v(d,"IFrame ("+_.id+") not found"),J=!1),J&&function(){var g=i.origin,u=t[d]&&t[d].checkOrigin;if(u&&""+g!="null"&&!function(){if(u.constructor!==Array)return M=t[d]&&t[d].remoteHost,a(d,"Checking connection is from: "+M),g===M;var M,k=0,P=!1;for(a(d,"Checking connection is from allowed list of origins: "+u);k<u.length;k++)if(u[k]===g){P=!0;break}return P}())throw Error("Unexpected message received from: "+g+" for "+_.iframe.id+". Message was: "+i.data+". This error can be disabled by setting the checkOrigin: false option or by providing of array of trusted domains.");return 1}()&&function(){var g,u,M,k,P;switch(t[d]&&t[d].firstRun&&t[d]&&(t[d].firstRun=!1),_.type){case"close":V(_.iframe);break;case"message":u=c(6),a(d,"onMessage passed: {iframe: "+_.iframe.id+", message: "+u+"}"),h("onMessage",{iframe:_.iframe,message:JSON.parse(u)}),a(d,"--");break;case"mouseenter":m("onMouseEnter");break;case"mouseleave":m("onMouseLeave");break;case"autoResize":t[d].autoResize=JSON.parse(c(9));break;case"scrollTo":I(!1);break;case"scrollToOffset":I(!0);break;case"pageInfo":w(t[d]&&t[d].iframe,d),g=d,B("Add ",s),t[g]&&(t[g].stopPageInfo=me);break;case"pageInfoStop":t[d]&&t[d].stopPageInfo&&(t[d].stopPageInfo(),delete t[d].stopPageInfo);break;case"inPageLink":c(9),P=decodeURIComponent(k=k.split("#")[1]||""),(P=document.getElementById(P)||document.getElementsByName(P)[0])?(P=r(P),a(d,"Moving to in page link (#"+k+") at x: "+P.x+" y: "+P.y),E={x:P.x,y:P.y},N(),a(d,"--")):window.top===window.self?a(d,"In page link #"+k+" not found"):window.parentIFrame?window.parentIFrame.moveToAnchor(k):a(d,"In page link #"+k+" not found and window.parentIFrame not found");break;case"reset":oe(_);break;case"init":o(),h("onInit",_.iframe);break;default:Number(_.width)===0&&Number(_.height)===0?v("Unsupported message received ("+_.type+"), this is likely due to the iframe containing a later version of iframe-resizer than the parent page"):o()}function B(ge,pe){function _e(){t[g]?w(t[g].iframe,g):me()}["scroll","resize"].forEach(function(fe){a(g,ge+fe+" listener for sendPageInfo"),pe(window,fe,_e)})}function me(){B("Remove ",f)}}())):C(d,"Ignored: "+L)}function U(i,o,l){var c=null,w=null;if(t[i]){if(typeof(c=t[i][o])!="function")throw TypeError(o+" on iFrame["+i+"] is not a function");w=c(l)}return w}function O(i){delete t[i=i.id]}function V(i){var o=i.id;if(U(o,"onClose",o)===!1)a(o,"Close iframe cancelled by onClose event");else{a(o,"Removing iFrame: "+o);try{i.parentNode&&i.parentNode.removeChild(i)}catch(l){v(l)}U(o,"onClosed",o),a(o,"--"),O(i)}}function $(i){E===null&&a(i,"Get page position: "+(E={x:window.pageXOffset===F?document.documentElement.scrollLeft:window.pageXOffset,y:window.pageYOffset===F?document.documentElement.scrollTop:window.pageYOffset}).x+","+E.y)}function q(i){E!==null&&(window.scrollTo(E.x,E.y),a(i,"Set page position: "+E.x+","+E.y),Y())}function Y(){E=null}function oe(i){a(i.id,"Size reset requested by "+(i.type==="init"?"host page":"iFrame")),$(i.id),de(function(){ae(i),x("reset","reset",i.iframe,i.id)},i,"reset")}function ae(i){function o(c){var w;w=c,i.id?(i.iframe.style[w]=i[w]+"px",a(i.id,"IFrame ("+l+") "+w+" set to "+i[w]+"px")):a("undefined","messageData id not set"),function(I){var N;function m(){Object.keys(t).forEach(function(h){var y;function j(te){return(t[y]&&t[y].iframe.style[te])==="0px"}t[y=h]&&t[y].iframe.offsetParent!==null&&(j("height")||j("width"))&&x("Visibility change","resize",t[y].iframe,y)})}!Z&&i[I]==="0"&&(Z=!0,a(l,"Hidden iFrame detected, creating visibility listener"),I=n())&&(N=document.querySelector("body"),new I(function(y){a("window","Mutation observed: "+y[0].target+" "+y[0].type),ie(m,16)}).observe(N,{attributes:!0,attributeOldValue:!1,characterData:!0,characterDataOldValue:!1,childList:!0,subtree:!0}))}(c)}var l=i.iframe.id;t[l]&&(t[l].sizeHeight&&o("height"),t[l].sizeWidth)&&o("width")}function de(i,o,l){l!==o.type&&S&&!window.jasmine?(a(o.id,"Requesting animation frame"),S(i)):i()}function x(i,o,l,c,w){var r,I=!1;t[c=c||l.id]&&(l&&"contentWindow"in l&&l.contentWindow!==null?(r=t[c]&&t[c].targetOrigin,a(c,"["+i+"] Sending msg to iframe["+c+"] ("+o+") targetOrigin: "+r),l.contentWindow.postMessage(b+o,r)):v(c,"["+i+"] IFrame("+c+") not found"),w&&t[c]&&t[c].warningTimeout&&(t[c].msgTimeout=setTimeout(function(){!t[c]||t[c].loaded||I||(I=!0,v(c,"IFrame has not responded within "+t[c].warningTimeout/1e3+" seconds. Check iFrameResizer.contentWindow.js has been loaded in iFrame. This message can be ignored if everything is working, or you can set the warningTimeout option to a higher value or zero to suppress this warning."))},t[c].warningTimeout)))}function ce(i){return i+":"+t[i].bodyMarginV1+":"+t[i].sizeWidth+":"+t[i].log+":"+t[i].interval+":"+t[i].enablePublicMethods+":"+t[i].autoResize+":"+t[i].bodyMargin+":"+t[i].heightCalculationMethod+":"+t[i].bodyBackground+":"+t[i].bodyPadding+":"+t[i].tolerance+":"+t[i].inPageLinks+":"+t[i].resizeFrom+":"+t[i].widthCalculationMethod+":"+t[i].mouseEvents}function he(i,o){function l(m){var h=m.split("Callback");h.length===2&&(this[h="on"+h[0].charAt(0).toUpperCase()+h[0].slice(1)]=this[m],delete this[m],v(r,"Deprecated: '"+m+"' has been renamed '"+h+"'. The old method will be removed in the next major version."))}var c,w,r=function(m){var h;if(typeof m!="string")throw TypeError("Invaild id for iFrame. Expected String");return m===""&&(i.id=(h=o&&o.id||z.id+D++,document.getElementById(h)!==null&&(h+=D++),m=h),K=(o||{}).log,a(m,"Added missing iframe ID: "+m+" ("+i.src+")")),m}(i.id);if(r in t&&"iFrameResizer"in i)v(r,"Ignored iFrame, already setup.");else{switch(function(h){if(h=h||{},t[r]=Object.create(null),t[r].iframe=i,t[r].firstRun=!0,t[r].remoteHost=i.src&&i.src.split("/").slice(0,3).join("/"),typeof h!="object")throw TypeError("Options is not an object");Object.keys(h).forEach(l,h);var y,j=h;for(y in z)Object.prototype.hasOwnProperty.call(z,y)&&(t[r][y]=(Object.prototype.hasOwnProperty.call(j,y)?j:z)[y]);t[r]&&(t[r].targetOrigin=t[r].checkOrigin!==!0||(h=t[r].remoteHost)===""||h.match(/^(about:blank|javascript:|file:\/\/)/)!==null?"*":h)}(o),a(r,"IFrame scrolling "+(t[r]&&t[r].scrolling?"enabled":"disabled")+" for "+r),i.style.overflow=(t[r]&&t[r].scrolling)===!1?"hidden":"auto",t[r]&&t[r].scrolling){case"omit":break;case!0:i.scrolling="yes";break;case!1:i.scrolling="no";break;default:i.scrolling=t[r]?t[r].scrolling:"no"}N("Height"),N("Width"),I("maxHeight"),I("minHeight"),I("maxWidth"),I("minWidth"),typeof(t[r]&&t[r].bodyMargin)!="number"&&(t[r]&&t[r].bodyMargin)!=="0"||(t[r].bodyMarginV1=t[r].bodyMargin,t[r].bodyMargin=t[r].bodyMargin+"px"),c=ce(r),(w=n())&&i.parentNode&&new w(function(m){m.forEach(function(h){Array.prototype.slice.call(h.removedNodes).forEach(function(y){y===i&&V(i)})})}).observe(i.parentNode,{childList:!0}),s(i,"load",function(){var m,h;x("iFrame.onload",c,i,F,!0),m=t[r]&&t[r].firstRun,h=t[r]&&t[r].heightCalculationMethod in X,!m&&h&&oe({iframe:i,height:0,width:0,type:"init"})}),x("init",c,i,F,!0),t[r]&&(t[r].iframe.iFrameResizer={close:V.bind(null,t[r].iframe),removeListeners:O.bind(null,t[r].iframe),resize:x.bind(null,"Window resize","resize",t[r].iframe),moveToAnchor:function(m){x("Move to anchor","moveToAnchor:"+m,t[r].iframe,r)},sendMessage:function(m){x("Send Message","message:"+(m=JSON.stringify(m)),t[r].iframe,r)}})}function I(m){var h=t[r][m];h!==1/0&&h!==0&&(i.style[m]=typeof h=="number"?h+"px":h,a(r,"Set "+m+" = "+i.style[m]))}function N(m){if(t[r]["min"+m]>t[r]["max"+m])throw Error("Value for min"+m+" can not be greater than max"+m)}}function ie(i,o){G===null&&(G=setTimeout(function(){G=null,i()},o))}function ue(){document.visibilityState!=="hidden"&&(a("document","Trigger event: Visibility change"),ie(function(){le("Tab Visible","resize")},16))}function le(i,o){Object.keys(t).forEach(function(l){var c;t[c=l]&&t[c].resizeFrom==="parent"&&t[c].autoResize&&!t[c].firstRun&&x(i,o,t[l].iframe,l)})}function ne(){function i(w,r){if(r){if(!r.tagName)throw TypeError("Object is not a valid DOM element");if(r.tagName.toUpperCase()!=="IFRAME")throw TypeError("Expected <IFRAME> tag, found <"+r.tagName+">");he(r,w),o.push(r)}}for(var o,l=["moz","webkit","o","ms"],c=0;c<l.length&&!S;c+=1)S=window[l[c]+"RequestAnimationFrame"];return S?S=S.bind(window):a("setup","RequestAnimationFrame not supported"),s(window,"message",H),s(window,"resize",function(){var w;a("window","Trigger event: "+(w="resize")),ie(function(){le("Window "+w,"resize")},16)}),s(document,"visibilitychange",ue),s(document,"-webkit-visibilitychange",ue),function(w,r){var I;switch(o=[],(I=w)&&I.enablePublicMethods&&v("enablePublicMethods option has been removed, public methods are now always available in the iFrame"),typeof r){case"undefined":case"string":Array.prototype.forEach.call(document.querySelectorAll(r||"iframe"),i.bind(F,w));break;case"object":i(w,r);break;default:throw TypeError("Unexpected data type ("+typeof r+")")}return o}}typeof window<"u"&&(D=0,Z=K=!1,ee=7,W=(b="[iFrameSizer]").length,E=null,S=window.requestAnimationFrame,X=Object.freeze({max:1,scroll:1,bodyScroll:1,documentElementScroll:1}),t={},G=null,z=Object.freeze({autoResize:!0,bodyBackground:null,bodyMargin:null,bodyMarginV1:8,bodyPadding:null,checkOrigin:!0,inPageLinks:!1,enablePublicMethods:!0,heightCalculationMethod:"bodyOffset",id:"iFrameResizer",interval:32,log:!1,maxHeight:1/0,maxWidth:1/0,minHeight:0,minWidth:0,mouseEvents:!0,resizeFrom:"parent",scrolling:!1,sizeHeight:!0,sizeWidth:!1,warningTimeout:5e3,tolerance:0,widthCalculationMethod:"scroll",onClose:function(){return!0},onClosed:function(){},onInit:function(){},onMessage:function(){v("onMessage function not defined")},onMouseEnter:function(){},onMouseLeave:function(){},onResized:function(){},onScroll:function(){return!0}}),R={},window.jQuery!==F&&((e=window.jQuery).fn?e.fn.iFrameResize||(e.fn.iFrameResize=function(i){return this.filter("iframe").each(function(o,l){he(l,i)}).end()}):C("","Unable to bind to jQuery, it is not fully loaded.")),typeof define=="function"&&define.amd?define([],ne):typeof module=="object"&&typeof module.exports=="object"&&(module.exports=ne()),window.iFrameResize=window.iFrameResize||ne())})(),function(F){"use strict";const D="opnform:",K=["utm_source","utm_medium","utm_campaign","utm_id","utm_term","utm_content","utm_source_platform","utm_creative_format","utm_marketing_tactic","gclid","gbraid","wbraid","dclid","fbclid","ttclid","msclkid"];function ee(){const R=new URLSearchParams(window.location.search);return K.reduce((e,n)=>{const s=R.getAll(n).find(f=>f.trim()!==""&&f.length<=2048);return s!==void 0&&(e[n]=s),e},{})}const b={READY:"ready",SUBMIT:"submit",SUBMIT_START:"submitStart",SUBMIT_ERROR:"submitError",RESET:"reset",PAGE_CHANGE:"pageChange",NEXT_PAGE:"nextPage",PREVIOUS_PAGE:"previousPage",DATA_CHANGE:"dataChange",ERROR:"error",SHOW:"show",HIDE:"hide",RESIZE:"resize"};function W(){return F.crypto?.randomUUID?F.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function E(R){try{return R?.src?new URL(R.src,window.location.href).origin:null}catch{return null}}function S(R){try{return R?.src?new URL(R.src,window.location.href).searchParams.get("_sdkToken"):null}catch{return null}}class X{constructor(){this._listeners={},this._onceListeners={}}on(e,n){return Array.isArray(e)?(e.forEach(s=>this.on(s,n)),this):(this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(n),this)}once(e,n){return this._onceListeners[e]||(this._onceListeners[e]=[]),this._onceListeners[e].push(n),this}off(e,n){return n?(this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(s=>s!==n)),this._onceListeners[e]&&(this._onceListeners[e]=this._onceListeners[e].filter(s=>s!==n)),this):(delete this._listeners[e],delete this._onceListeners[e],this)}emit(e,n){if(this._listeners[e]&&this._listeners[e].forEach(s=>{try{s(n)}catch(f){console.error("[OpnForm SDK] Error in event handler:",f)}}),this._onceListeners[e]){const s=this._onceListeners[e];delete this._onceListeners[e],s.forEach(f=>{try{f(n)}catch(p){console.error("[OpnForm SDK] Error in once handler:",p)}})}}}class t extends X{constructor(e,n,s,f=null){super(),this.iframe=e,this.slug=n,this.id=e.id||n,this._sdk=s,this._sdkToken=f||S(e)||W(),this._ready=!1,this._pendingRequests={},this._requestId=0,this._cachedData={},this._cachedErrors={},this._darkMode=!1,this._currentPage={index:0,total:1},this._popupOpen=!1,this._resizeInitialized=!1,this._targetOrigin=E(e)||"*",this._handshakeComplete=!1,this._handshakePromise=null,this._handshakeResolve=null,this._handshakeReject=null,this._handshakeRetryTimer=null}isReady(){return this._ready}_sendHandshake(){!this.iframe?.contentWindow||!this._sdkToken||this.iframe.contentWindow.postMessage({type:D+"handshake",formSlug:this.slug,_sdkToken:this._sdkToken,parentOrigin:window.location.origin,trackingParameters:ee()},this._targetOrigin)}_createHandshakePromise(){return new Promise((e,n)=>{this._handshakeResolve=e,this._handshakeReject=n,this._sendHandshake(),this._handshakeRetryTimer=setInterval(()=>{this._handshakeComplete||this._sendHandshake()},250),setTimeout(()=>{this._handshakeComplete||(this._handshakeRetryTimer&&(clearInterval(this._handshakeRetryTimer),this._handshakeRetryTimer=null),this._handshakePromise=null,this._handshakeResolve=null,this._handshakeReject&&(this._handshakeReject(new Error("SDK handshake timeout")),this._handshakeReject=null))},3e3)})}_startHandshake(){this._handshakePromise=this._createHandshakePromise(),this._handshakePromise.catch(()=>{}),this.iframe.contentWindow?this._sendHandshake():this.iframe.addEventListener("load",()=>this._sendHandshake())}_ensureHandshake(){return this._handshakeComplete?Promise.resolve():(this._handshakePromise||(this._handshakePromise=this._createHandshakePromise()),this._handshakePromise)}_handleHandshakeAck(e){if(this._handshakeRetryTimer&&(clearInterval(this._handshakeRetryTimer),this._handshakeRetryTimer=null),e.success===!1){this._handshakePromise=null,this._handshakeResolve=null,this._handshakeReject&&(this._handshakeReject(new Error("SDK handshake rejected")),this._handshakeReject=null);return}this._handshakeComplete=!0,this._handshakeResolve&&(this._handshakeResolve(),this._handshakeResolve=null,this._handshakeReject=null)}_sendCommand(e,n={}){return!this.iframe||!this.iframe.contentWindow?(console.warn("[OpnForm SDK] Cannot send command - iframe not available"),Promise.reject(new Error("Iframe not available"))):this._ensureHandshake().then(()=>{const s=++this._requestId,f={type:D+"command",command:e,formSlug:this.slug,requestId:s,payload:n,_sdkToken:this._sdkToken};return new Promise((p,a)=>{this._pendingRequests[s]={resolve:p,reject:a},setTimeout(()=>{this._pendingRequests[s]&&(delete this._pendingRequests[s],a(new Error("Command timeout")))},5e3),this.iframe.contentWindow.postMessage(f,this._targetOrigin)})})}matchesMessageSource(e){return!this.iframe||e.source!==this.iframe.contentWindow?!1:this._targetOrigin==="*"||e.origin===this._targetOrigin}_handleResponse(e){const n=this._pendingRequests[e.requestId];n&&(delete this._pendingRequests[e.requestId],e.success?n.resolve(e.data):n.reject(new Error(e.error||"Command failed")))}getField(e){return this._cachedData[e]}setField(e,n){return this._sendCommand("setField",{fieldId:e,value:n})}setFields(e){return this._sendCommand("setFields",{data:e})}getData(){return{...this._cachedData}}clearField(e){return this._sendCommand("clearField",{fieldId:e})}clearAll(){return this._sendCommand("clearAll",{})}hasError(e){return!!this._cachedErrors[e]}getError(e){return this._cachedErrors[e]||null}getErrors(){return{...this._cachedErrors}}isFieldVisible(e){return this._sendCommand("isFieldVisible",{fieldId:e})}toggleDarkMode(){return this.setDarkMode(!this._darkMode)}setDarkMode(e){return this._darkMode=e==="auto"?null:!!e,this._sendCommand("setDarkMode",{enabled:e})}isDarkMode(){return this._darkMode}setTheme(e){return this._sendCommand("setTheme",{theme:e})}goToPage(e){return this._sendCommand("goToPage",{index:e})}nextPage(){return this._sendCommand("nextPage",{})}previousPage(){return this._sendCommand("previousPage",{})}getCurrentPage(){return{...this._currentPage}}canGoNext(){return this._currentPage.index<this._currentPage.total-1}canGoPrevious(){return this._currentPage.index>0}submit(){return this._sendCommand("submit",{})}reset(){return this._sendCommand("reset",{})}focusFirstError(){return this._sendCommand("focusFirstError",{})}open(){const e=document.querySelector(".nf-main");e&&(e.classList.add("open"),this._popupOpen=!0,this.emit(b.SHOW,{form:this._getFormInfo()}))}close(){const e=document.querySelector(".nf-main");e&&(e.classList.remove("open"),this._popupOpen=!1,this.emit(b.HIDE,{form:this._getFormInfo()}))}toggle(){this._popupOpen?this.close():this.open()}isOpen(){return this._popupOpen}_getFormInfo(){return{slug:this.slug,id:this.id}}initResize(){this._resizeInitialized||F.iFrameResize&&this.iframe&&(F.iFrameResize({log:!1},this.iframe),this._resizeInitialized=!0)}}class G extends X{constructor(){super(),this._forms={},this._options={autoResize:!0,defaultDarkMode:"auto",preventRedirect:!1},this._initialized=!1,this._messageHandler=this._handleMessage.bind(this),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this._autoInit()):this._autoInit()}init(e={}){if(this._options={...this._options,...e},this._initialized||(window.addEventListener("message",this._messageHandler),this._initialized=!0),this._discoverForms(),this._options.onReady&&Object.keys(this._forms).length>0){const n=Object.values(this._forms).filter(s=>s.isReady());n.length>0&&this._options.onReady(n)}}_autoInit(){window.addEventListener("message",this._messageHandler),this._initialized=!0,this._discoverForms()}_discoverForms(){document.querySelectorAll("iframe").forEach(n=>{const s=n.src||"";if(s.includes("/forms/")&&!this._forms[n.id]){const f=s.match(/\/forms\/([^/?#]+)/),p=f?f[1]:n.id;p&&this._registerForm(n,p)}})}_registerForm(e,n,s=null){const f=new t(e,n,this,s);return this._forms[n]=f,e.id&&e.id!==n&&(this._forms[e.id]=f),f._startHandshake(),this._options.autoResize!==!1&&(e.contentWindow?f.initResize():e.addEventListener("load",()=>f.initResize())),f}_handleMessage(e){const n=e.data;if(!(!n||typeof n!="object")){if(n.type==="form-submitted"){const s=this._forms[n.form?.slug];s?.matchesMessageSource(e)&&this._handleLegacySubmit(n,s);return}if(n.type&&n.type.startsWith&&n.type.startsWith(D)){const s=this._forms[n.formSlug];if(!s?.matchesMessageSource(e))return;const f=n.type.replace(D,"");f==="event"?this._handleEvent(n,s):f==="response"?this._handleResponse(n,s):f==="handshake-ack"&&s._handleHandshakeAck(n)}}}_handleLegacySubmit(e,n=null){const s=e.form?.slug;n=n||this._forms[s];const f={form:{slug:s,id:e.form?.id},data:e.submission_data||{},submissionId:e.submission_id,completionTime:e.completion_time};n&&(n._cachedData=f.data,n.emit(b.SUBMIT,f)),this.emit(b.SUBMIT,f),!this._options.preventRedirect&&e.form?.redirect_target_url&&(window.top.location.href=e.form.redirect_target_url)}_handleEvent(e,n=null){const{event:s,formSlug:f,payload:p}=e;if(n=n||this._forms[f],!n)return;switch(s){case b.READY:n._ready=!0,p.data&&(n._cachedData=p.data),p.currentPage&&(n._currentPage=p.currentPage),p.darkMode!==void 0&&(n._darkMode=p.darkMode);break;case b.DATA_CHANGE:n._cachedData=p.data||{};break;case b.ERROR:n._cachedErrors=p.errors||{};break;case b.SUBMIT:n._cachedData=p.data||{};break;case b.SUBMIT_ERROR:n._cachedErrors=p.errors||{};break;case b.PAGE_CHANGE:case b.NEXT_PAGE:case b.PREVIOUS_PAGE:p.currentPage!==void 0&&(n._currentPage.index=p.currentPage),p.toPage!==void 0&&(n._currentPage.index=p.toPage),p.totalPages!==void 0&&(n._currentPage.total=p.totalPages);break;case b.RESET:n._cachedData={},n._cachedErrors={},n._currentPage={index:0,total:n._currentPage.total};break}const a={form:n._getFormInfo(),...p};if(n.emit(s,a),this.emit(s,a),s===b.READY&&this._options.onReady){const C=Object.values(this._forms),v=[...new Set(C)];v.every(A=>A.isReady())&&this._options.onReady(v)}}_handleResponse(e,n=null){const{formSlug:s,requestId:f,success:p,data:a,error:C}=e;n=n||this._forms[s],n&&n._handleResponse({requestId:f,success:p,data:a,error:C})}get(e){return this._forms[e]||null}getAll(){const e=Object.values(this._forms);return[...new Set(e)]}isReady(e){const n=this._forms[e];return n?n.isReady():!1}create(e,n={}){const{container:s,baseUrl:f="https://opnform.com",width:p="100%",height:a="auto",darkMode:C,onSubmit:v}=n;let A=s;if(typeof s=="string"&&(A=document.querySelector(s)),!A)return console.error("[OpnForm SDK] Container element not found"),null;let H,U;try{if(typeof e!="string"||!e.trim())throw new Error("Missing form slug or URL");const q=/^[a-z][a-z\d+.-]*:/i.test(e);if(!q&&/[/?#\s]/.test(e))throw new Error("Invalid form slug");H=new URL(q?e:`${f.replace(/\/+$/,"")}/forms/${encodeURIComponent(e)}`);const Y=H.pathname.match(/\/forms\/([^/]+)\/?$/);if(!["http:","https:"].includes(H.protocol)||!Y)throw new Error("Invalid form URL");U=decodeURIComponent(Y[1])}catch(q){return console.error("[OpnForm SDK] Invalid form slug, URL or baseUrl:",q.message),null}const O=document.createElement("iframe");O.id=U,O.style.border="none",O.style.width=p,O.style.height=a==="auto"?"600px":a;const V=W();H.searchParams.set("_sdkToken",V),H.searchParams.set("_sdkParentOrigin",window.location.origin),C!==void 0&&H.searchParams.set("darkMode",String(C)),O.src=H.toString(),A.appendChild(O);const $=this._registerForm(O,U,V);return v&&$.on(b.SUBMIT,v),$}initAutoResize(e){const n=this._forms[e];if(n)n.initResize();else if(F.iFrameResize){const s="#"+e;F.iFrameResize({log:!1},s)}}}const z=new G;F.opnform=z,F.initEmbed||(F.initEmbed=function(R,e={}){z.init(e);const n=z.get(R);n&&n.on("submit",s=>{s.form?.redirect_target_url&&(window.top.location.href=s.form.redirect_target_url)}),e.autoResize!==!1&&z.initAutoResize(R)})}(typeof window<"u"?window:void 0);
diff --git a/client/test/unit/opnform-sdk-postmessage.test.ts b/client/test/unit/opnform-sdk-postmessage.test.ts
index 313564284..e9a037a94 100644
--- a/client/test/unit/opnform-sdk-postmessage.test.ts
+++ b/client/test/unit/opnform-sdk-postmessage.test.ts
@@ -216,20 +216,26 @@ describe('OpnForm public SDK postMessage security', () => {
}
})
- it('includes the SDK token when creating a form iframe', async () => {
+ it.each([
+ ['source', sdkSource],
+ ['minified', sdkMinSource],
+ ])('creates form iframes on OpnForm by default with a working SDK handshake (%s)', async (_variant, source) => {
const dom = new JSDOM('<!doctype html><html><body><div id="container"></div></body></html>', {
url: 'https://embedder.example.test/',
runScripts: 'outside-only',
})
- dom.window.eval(sdkSource)
+ dom.window.eval(source)
dom.window.opnform.init({ autoResize: false })
const form = dom.window.opnform.create('demo', { container: '#container' })
const iframe = dom.window.document.querySelector('iframe') as HTMLIFrameElement
- expect(iframe.src).toContain('_sdkToken=')
- expect(iframe.src).toContain('_sdkParentOrigin=')
+ const url = new URL(iframe.src)
+ expect(url.origin).toBe('https://opnform.com')
+ expect(url.pathname).toBe('/forms/demo')
+ expect(url.searchParams.get('_sdkToken')).toBeTruthy()
+ expect(url.searchParams.get('_sdkParentOrigin')).toBe('https://embedder.example.test')
mockIframePostMessage(dom.window, iframe)
simulateHandshakeAck(dom.window, iframe)
@@ -240,8 +246,141 @@ describe('OpnForm public SDK postMessage security', () => {
type: 'opnform:command',
_sdkToken: expect.any(String),
}),
- 'https://embedder.example.test',
+ 'https://opnform.com',
)
+ dom.window.close()
+ })
+
+ describe.each([
+ ['source', sdkSource],
+ ['minified', sdkMinSource],
+ ])('programmatic form URLs (%s)', (_variant, source) => {
+ it.each([
+ 'https://forms.example.test',
+ 'https://example.test/',
+ 'http://localhost:3212///',
+ ])('loads the form from %s and sends commands to that origin', async (baseUrl) => {
+ const dom = new JSDOM('<!doctype html><html><body><div id="container"></div></body></html>', {
+ url: 'https://embedder.example.test/',
+ runScripts: 'outside-only',
+ })
+
+ dom.window.eval(source)
+ dom.window.opnform.init({ autoResize: false })
+ const form = dom.window.opnform.create('demo', {
+ container: '#container',
+ baseUrl,
+ darkMode: true,
+ })
+ const iframe = dom.window.document.querySelector('iframe') as HTMLIFrameElement
+ const url = new URL(iframe.src)
+
+ expect(url.origin).toBe(new URL(baseUrl).origin)
+ expect(url.pathname).toBe('/forms/demo')
+ expect(url.searchParams.get('darkMode')).toBe('true')
+ expect(url.searchParams.get('_sdkToken')).toBeTruthy()
+ expect(url.searchParams.get('_sdkParentOrigin')).toBe('https://embedder.example.test')
+
+ mockIframePostMessage(dom.window, iframe)
+ simulateHandshakeAck(dom.window, iframe)
+ await form.setField('email', '[email protected]')
+
+ expect(iframe.contentWindow!.postMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'opnform:command', _sdkToken: expect.any(String) }),
+ url.origin,
+ )
+ dom.window.close()
+ })
+
+ it.each([
+ 'https://opnform.com/forms/demo',
+ 'https://example.test/forms/demo/',
+ 'https://forms.example.test/forms/demo',
+ 'http://localhost:3212/forms/demo',
+ ])('uses the full URL %s ahead of baseUrl and registers the form by slug', async (formUrl) => {
+ const dom = new JSDOM('<!doctype html><html><body><div id="container"></div></body></html>', {
+ url: 'https://embedder.example.test/',
+ runScripts: 'outside-only',
+ })
+ dom.window.eval(source)
+ dom.window.opnform.init({ autoResize: false })
+ const onSubmit = vi.fn()
+ const form = dom.window.opnform.create(formUrl, {
+ container: '#container',
+ baseUrl: 'https://ignored.example.test',
+ onSubmit,
+ })
+ const iframe = dom.window.document.querySelector('iframe') as HTMLIFrameElement
+ const url = new URL(iframe.src)
+
+ expect(url.origin + url.pathname).toBe(formUrl)
+ expect(iframe.id).toBe('demo')
+ expect(dom.window.opnform.get('demo')).toBe(form)
+ expect(url.searchParams.get('_sdkParentOrigin')).toBe('https://embedder.example.test')
+
+ mockIframePostMessage(dom.window, iframe)
+ simulateHandshakeAck(dom.window, iframe)
+ await form.setField('email', '[email protected]')
+ expect(iframe.contentWindow!.postMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'opnform:command', formSlug: 'demo' }),
+ url.origin,
+ )
+
+ dom.window.dispatchEvent(new dom.window.MessageEvent('message', {
+ data: { type: 'opnform:event', event: 'submit', formSlug: 'demo', payload: { data: { email: '[email protected]' } } },
+ origin: url.origin,
+ source: iframe.contentWindow,
+ }))
+ expect(onSubmit).toHaveBeenCalledOnce()
+ dom.window.close()
+ })
+
+ it.each([undefined, false])('preserves URL parameters and fragment while applying explicit darkMode=%s', (darkMode) => {
+ const dom = new JSDOM('<!doctype html><html><body><div id="container"></div></body></html>', {
+ url: 'https://embedder.example.test/',
+ runScripts: 'outside-only',
+ })
+ dom.window.eval(source)
+ dom.window.opnform.init({ autoResize: false })
+ dom.window.opnform.create('https://example.test/forms/demo?email=user%40example.test&tag=a&tag=b&darkMode=true&_sdkToken=old&_sdkParentOrigin=https%3A%2F%2Fold.example.test#section', {
+ container: '#container',
+ darkMode,
+ })
+ const iframe = dom.window.document.querySelector('iframe') as HTMLIFrameElement
+ const url = new URL(iframe.src)
+
+ expect(url.searchParams.get('email')).toBe('[email protected]')
+ expect(url.searchParams.getAll('tag')).toEqual(['a', 'b'])
+ expect(url.searchParams.get('darkMode')).toBe(darkMode === undefined ? 'true' : 'false')
+ expect(url.searchParams.get('_sdkToken')).toBeTruthy()
+ expect(url.searchParams.get('_sdkToken')).not.toBe('old')
+ expect(url.searchParams.get('_sdkParentOrigin')).toBe('https://embedder.example.test')
+ expect(url.hash).toBe('#section')
+ simulateHandshakeAck(dom.window, iframe)
+ dom.window.close()
+ })
+
+ it.each([
+ '',
+ 'https://',
+ 'https://example.test/',
+ 'https://example.test/forms/',
+ 'https://example.test/forms/demo/edit',
+ '//example.test/forms/demo',
+ 'javascript:alert(1)',
+ 'ftp://example.test/forms/demo',
+ ])('rejects invalid form input %s without inserting an iframe', (formInput) => {
+ const dom = new JSDOM('<!doctype html><html><body><div id="container"></div></body></html>', {
+ url: 'https://embedder.example.test/',
+ runScripts: 'outside-only',
+ })
+ dom.window.eval(source)
+ vi.spyOn(dom.window.console, 'error').mockImplementation(() => {})
+
+ expect(dom.window.opnform.create(formInput, { container: '#container' })).toBeNull()
+ expect(dom.window.document.querySelector('iframe')).toBeNull()
+ dom.window.close()
+ })
})
it('rejects commands when handshake times out without ack', async () => {
diff --git a/docs/embedding/javascript-sdk.mdx b/docs/embedding/javascript-sdk.mdx
index 323024aa2..4ac897e59 100644
--- a/docs/embedding/javascript-sdk.mdx
+++ b/docs/embedding/javascript-sdk.mdx
@@ -303,6 +303,12 @@ opnform.init({
### Programmatic Form Creation
+Use `opnform.create(slugOrUrl, options)` to create an iframe for an existing
+form. Pass either its slug or its full share URL.
+
+With a slug, the iframe loads from `https://opnform.com` by default, regardless
+of your page's domain or where you load the SDK script.
+
```javascript
opnform.create("my-form-slug", {
container: "#form-container", // CSS selector or element
@@ -315,6 +321,41 @@ opnform.create("my-form-slug", {
});
```
+If you have the form's share URL, pass it directly. This works with OpnForm
+Cloud, custom domains, subdomains, and self-hosted instances:
+
+```javascript
+opnform.create("https://forms.example.com/forms/my-form-slug?email=user%40example.com", {
+ container: "#form-container",
+});
+```
+
+The URL must use `http://` or `https://` and point to a public form at
+`/forms/{slug}`. Its query parameters and fragment are preserved. You can
+access the resulting form with `opnform.get("my-form-slug")` as usual.
+
+If you only have the slug, pass `baseUrl` to select a custom domain or a
+self-hosted instance. Include the protocol:
+
+```javascript
+opnform.create("my-form-slug", {
+ container: "#form-container",
+ baseUrl: "https://forms.example.com",
+});
+```
+
+This loads `https://forms.example.com/forms/my-form-slug` inside the iframe.
+
+- A full URL takes precedence over `baseUrl`; its host is never replaced.
+- With a slug, `baseUrl` defaults to `https://opnform.com`. The SDK does not
+ look up the form's custom domain automatically.
+- An explicit `darkMode` option overrides the value in the URL. The SDK sets
+ its own `_sdkToken` and `_sdkParentOrigin` parameters for iframe communication.
+- Existing iframes keep their own `src`.
+
+If your integration previously relied on `create()` loading from the page's
+domain, pass that instance's `baseUrl` explicitly or use the full share URL.
+
---
## Integration Examples
diff --git a/docs/front-end/javascript-sdk.mdx b/docs/front-end/javascript-sdk.mdx
index 9d723361d..42e756a65 100644
--- a/docs/front-end/javascript-sdk.mdx
+++ b/docs/front-end/javascript-sdk.mdx
@@ -302,6 +302,12 @@ opnform.init({
### Programmatic Form Creation
+Use `opnform.create(slugOrUrl, options)` to create an iframe for an existing
+form. Pass either its slug or its full share URL.
+
+With a slug, the iframe loads from `https://opnform.com` by default, regardless
+of your page's domain or where you load the SDK script.
+
```javascript
opnform.create("my-form-slug", {
container: "#form-container", // CSS selector or element
@@ -314,6 +320,41 @@ opnform.create("my-form-slug", {
});
```
+If you have the form's share URL, pass it directly. This works with OpnForm
+Cloud, custom domains, subdomains, and self-hosted instances:
+
+```javascript
+opnform.create("https://forms.example.com/forms/my-form-slug?email=user%40example.com", {
+ container: "#form-container",
+});
+```
+
+The URL must use `http://` or `https://` and point to a public form at
+`/forms/{slug}`. Its query parameters and fragment are preserved. You can
+access the resulting form with `opnform.get("my-form-slug")` as usual.
+
+If you only have the slug, pass `baseUrl` to select a custom domain or a
+self-hosted instance. Include the protocol:
+
+```javascript
+opnform.create("my-form-slug", {
+ container: "#form-container",
+ baseUrl: "https://forms.example.com",
+});
+```
+
+This loads `https://forms.example.com/forms/my-form-slug` inside the iframe.
+
+- A full URL takes precedence over `baseUrl`; its host is never replaced.
+- With a slug, `baseUrl` defaults to `https://opnform.com`. The SDK does not
+ look up the form's custom domain automatically.
+- An explicit `darkMode` option overrides the value in the URL. The SDK sets
+ its own `_sdkToken` and `_sdkParentOrigin` parameters for iframe communication.
+- Existing iframes keep their own `src`.
+
+If your integration previously relied on `create()` loading from the page's
+domain, pass that instance's `baseUrl` explicitly or use the full share URL.
+
---
## Integration Examples