JavaScript SDK
The SharaForms JavaScript SDK enables you to programmatically control embedded forms, listen to events, and build dynamic integrations. The SDK is available globally as window.sharaforms (or the legacy window.opnform alias). It includes automatic iframe resizing and full backward compatibility with existing embeds.
The SharaForms JavaScript SDK enables you to programmatically control embedded forms, listen to events, and build dynamic integrations. The SDK is available globally as window.sharaforms (or the legacy window.opnform alias). It includes automatic iframe resizing and full backward compatibility with existing embeds.
#Installation
Include the SDK script after your form iframe:
<iframe
id="my-form"
src="https://sharaforms.com/forms/my-form-slug"
style="border:none;width:100%;"
></iframe>
<script src="https://sharaforms.com/widgets/sharaforms-sdk.min.js"></script>Note
The SDK automatically discovers SharaForms iframes on your page and initializes them. No additional setup required.
#Quick Start
// Listen to form submission
sharaforms.on("submit", function (data) {
console.log("Form submitted!", data);
console.log("Submission data:", data.data);
});
// Set a field value
sharaforms.get("my-form").setField("email", "[email protected]");
// Toggle dark mode
sharaforms.get("my-form").toggleDarkMode();#Events
Listen to form events to trigger custom actions, send data to analytics, or integrate with your application.
#Available Events
| Event | Description | Payload |
|---|---|---|
ready | Form iframe loaded and ready | { form, slug, id } |
submit | Form submitted successfully | { form, data, submissionId, completionTime } |
submitStart | Submission started | { form } |
submitError | Submission failed | { form, errors } |
dataChange | Form data changed | { form, data, changedField, previousValue, newValue } |
error | Validation error occurred | { form, errors } |
pageChange | Page navigation (multi-page forms) | { form, fromPage, toPage, totalPages } |
nextPage | User proceeded to next page | { form, currentPage, totalPages } |
previousPage | User went back | { form, currentPage, totalPages } |
reset | Form was reset | { form } |
show | Popup form opened | { form } |
hide | Popup form closed | { form } |
#Listening to Events
sharaforms.on('submit', function(data) {
console.log('Form submitted:', data);
});sharaforms.on(["nextPage", "previousPage"], function (data) {
console.log("Page changed to:", data.currentPage);
});sharaforms.get("contact-form").on("submit", function (data) {
console.log("Contact form submitted");
});sharaforms.once("ready", function (data) {
console.log("Form is ready");
});#Removing Event Listeners
// Remove specific handler
const handler = (data) => console.log(data);
sharaforms.on("submit", handler);
sharaforms.off("submit", handler);
// Remove all listeners for an event
sharaforms.off("submit");#Form Methods
Access form instances using sharaforms.get('form-slug') (or legacy sharaforms.get('form-slug')) and call methods to control the form.
#Field Operations
#Error Handling
// Check if a field has an error
const hasError = sharaforms.get("my-form").hasError("email");
// Get error message for a field
const errorMsg = sharaforms.get("my-form").getError("email");
// Get all errors
const errors = sharaforms.get("my-form").getErrors();
// { email: "Invalid email format", phone: "Required" }#Theme Control
// Toggle dark mode
sharaforms.get("my-form").toggleDarkMode();
// Set specific mode
sharaforms.get("my-form").setDarkMode(true); // Dark
sharaforms.get("my-form").setDarkMode(false); // Light
sharaforms.get("my-form").setDarkMode("auto"); // Follow system
// Check current mode
const isDark = sharaforms.get("my-form").isDarkMode();#Navigation (Multi-Page Forms)
// Navigate to specific page
sharaforms.get("my-form").goToPage(2);
// Navigate forward/backward
sharaforms.get("my-form").nextPage();
sharaforms.get("my-form").previousPage();
// Get current page info
const page = sharaforms.get("my-form").getCurrentPage();
// { index: 1, total: 4 }
// Check navigation availability
const canNext = sharaforms.get("my-form").canGoNext();
const canPrev = sharaforms.get("my-form").canGoPrevious();#Form Actions
// Submit form programmatically
sharaforms.get("my-form").submit();
// Reset form to initial state
sharaforms.get("my-form").reset();
// Focus on first error field
sharaforms.get("my-form").focusFirstError();#Popup Control
For forms embedded as popups:
// Open popup
sharaforms.get("my-form").open();
// Close popup
sharaforms.get("my-form").close();
// Toggle popup
sharaforms.get("my-form").toggle();
// Check if open
const isOpen = sharaforms.get("my-form").isOpen();#Global SDK Methods
#Form Management
// Get a specific form instance
const form = sharaforms.get("my-form-slug");
// Get all forms on the page
const forms = sharaforms.getAll();
// Check if a form is ready
const isReady = sharaforms.isReady("my-form-slug");#Initialization Options
sharaforms.init({
autoResize: true, // Auto-resize iframes (default: true)
defaultDarkMode: "auto", // 'auto' | true | false
preventRedirect: false, // Prevent redirect after submission
onReady: function (forms) {
// Callback when all forms ready
console.log("All forms ready:", forms);
},
});#Programmatic Form Creation
sharaforms.create("my-form-slug", {
container: "#form-container", // CSS selector or element
width: "100%",
height: "auto",
darkMode: false,
onSubmit: function (data) {
console.log("Submitted:", data);
},
});#Integration Examples
#Google Analytics 4
sharaforms.on("submit", function (data) {
gtag("event", "form_submission", {
form_id: data.form.id,
form_name: data.form.slug,
completion_time: data.completionTime,
});
});
sharaforms.on("pageChange", function (data) {
gtag("event", "form_progress", {
form_id: data.form.id,
current_page: data.toPage,
total_pages: data.totalPages,
});
});#Send to Custom API
sharaforms.on("submit", async function (data) {
await fetch("/api/leads", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: data.data.email,
name: data.data.name,
source: "opnform",
formId: data.form.id,
}),
});
});#Error Tracking
sharaforms.on("submitError", function (data) {
console.error("Form submission failed:", data.errors);
// Send to error tracking service
Sentry.captureMessage("Form submission failed", {
extra: { formId: data.form.id, errors: data.errors },
});
});
sharaforms.on("error", function (data) {
console.log("Validation errors:", data.errors);
});#Dynamic Field Population
sharaforms.once("ready", function () {
// Get data from URL params
const params = new URLSearchParams(window.location.search);
sharaforms.get("my-form").setFields({
email: params.get("email") || "",
utm_source: params.get("utm_source") || "direct",
utm_campaign: params.get("utm_campaign") || "",
});
});#Custom Code Integration
The SDK is automatically available when using the Custom Code feature in SharaForms. You can add custom JavaScript directly in your form or workspace settings, and the window.sharaforms (or legacy window.opnform) SDK will be ready to use.
Tip
Custom Code works without iframes - the SDK is initialized directly on your form page, giving you full access to form methods and events.
#Adding Custom Code
- Go to your form's Settings → Custom Code (or Workspace Settings for workspace-wide code)
- Add your JavaScript code in a
<script>tag - The SDK (
window.sharaformsor legacywindow.opnform) is automatically available
#Example: Google Analytics Tracking
<script>
// Track form submission
sharaforms.on("submit", function (data) {
gtag("event", "form_submission", {
form_slug: data.form.slug,
submission_id: data.submissionId,
});
});
// Track page progress
sharaforms.on("pageChange", function (data) {
gtag("event", "form_progress", {
page: data.toPage + 1,
total_pages: data.totalPages,
});
});
</script>#Example: Facebook Pixel
<script>
sharaforms.on("submit", function (data) {
fbq("track", "Lead", {
content_name: data.form.slug,
});
});
</script>#Example: Conditional Logic with External Data
<script>
sharaforms.once("ready", function () {
// Fetch user data and pre-fill form
fetch("/api/user-info")
.then((r) => r.json())
.then((user) => {
sharaforms.get("my-form").setFields({
email: user.email,
name: user.name,
});
});
});
</script>#Example: Custom Validation Feedback
<script>
sharaforms.on("error", function (data) {
// Show custom toast notification for errors
Object.values(data.errors).forEach(function (error) {
showToast(error, "error");
});
});
sharaforms.on("submit", function (data) {
showToast("Thank you for your submission!", "success");
});
</script>#Example: Live Data Change Tracking
<script>
sharaforms.on("dataChange", function (data) {
console.log("Field changed:", data.changedField);
console.log("New value:", data.newValue);
// Example: Show/hide elements based on form data
if (data.changedField === "country" && data.newValue === "US") {
document.querySelector(".us-only-info").style.display = "block";
}
});
</script>#Accessing Form Data Directly
<script>
sharaforms.once("ready", function () {
var form = sharaforms.get("my-form-slug");
// Get all current form data
var data = form.getData();
console.log("Current form data:", data);
// Get specific field value
var email = form.getField("email");
// Check if field has validation error
if (form.hasError("email")) {
console.log("Email error:", form.getError("email"));
}
// Get current page (for multi-page forms)
var page = form.getCurrentPage();
console.log("Page " + (page.index + 1) + " of " + page.total);
});
</script>#Backward Compatibility
Info
Existing embeds using initEmbed() or the window.opnform global continue to work without changes. The SDK provides full backward compatibility. New code should use window.sharaforms as the primary API.
<!-- Old embed code still works (legacy URL) -->
<iframe id="my-form" src="https://sharaforms.com/forms/my-form"></iframe>
<script src="https://sharaforms.com/widgets/iframe.min.js"></script>
<script>
initEmbed("my-form", { autoResize: true });
</script>Tip
We recommend upgrading to the new SDK to access event callbacks and programmatic control features.