This guide is designed to help platform developers seamlessly embed Straddle’s instant onboarding components into your application

Implementation Overview

Before embedding a Straddle form, you need to create an organization for each of your clients and obtain its unique ID (organization_id). This ID links the form to the specific organization within your platform.

Creating an Organization

Make a POST request to the Straddle API to create an organization:

curl --request POST \
  --url https://production.straddle.io/v1/organizations \
  --header 'Authorization: Bearer <api-key>' \
  --header 'Content-Type: application/json' \
  --data '{
    "name": "<string>",
    "metadata": {},
    "external_id": "<string>"
}'
  • Authorization: Replace <api-key> with your actual API key.

  • Data Fields:

    • name: The name of your client’s organization.

    • metadata: An optional object for additional data.

    • external_id: An optional external identifier for your internal mapping.

Sample API Response

{
  "meta": {
    "api_request_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
    "api_request_timestamp": "2023-11-07T05:31:56Z"
  },
  "response_type": "success",
  "data": {
    "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
    "name": "<string>",
    "external_id": "<string>",
    "metadata": {}
  }
}
  • Organization ID (organization_id): The id field (3c90c3cc-0d44-4b50-8888-8dd25736052a) is your client’s unique organization ID. You’ll use this ID in the embed URL.

Embedding Approaches

Approach 1: Quick Embed

This approach is ideal for developers seeking a plug-and-play solution. Simply add the script and iframe, and the embed loads automatically.

Full Example Usage

<!-- Straddle Embed Iframe -->
<iframe
  data-straddle-src="https://go.straddle.io/account?alignLeft=1&hideTitle=1&transparentBackground=1&dynamicHeight=1&embed=1&org={organization_id}"
  loading="lazy"
  width="100%"
  height="500"
  frameborder="0"
  title="Activate your Straddle account"
></iframe>

<!-- Straddle Embed Initialization Script -->
<script>
  (function () {
    'use strict';

    const workerUrl = 'https://forms.straddle.io/embed.js';
    const isDebugMode = false; // Set to true for debugging

    const initStraddleEmbed = () => {
      try {
        if (window.Straddle && typeof window.Straddle.loadEmbeds === 'function') {
          // Load embeds using the Straddle script
          window.Straddle.loadEmbeds();
        } else {
          // Fallback: Manually set iframe src attributes
          const iframes = document.querySelectorAll(
            'iframe[data-straddle-src]:not([src])'
          );

          // Check if NodeList.forEach is available
          if (typeof iframes.forEach === 'function') {
            iframes.forEach((iframe) => {
              if (isDebugMode) {
                console.log('Straddle: Setting src for iframe:', iframe);
              }
              const src =
                iframe.dataset?.straddleSrc ||
                iframe.getAttribute('data-straddle-src') ||
                '';
              iframe.src = src;
            });
          } else {
            // Fallback for older browsers
            for (let i = 0; i < iframes.length; i++) {
              const iframe = iframes[i];
              if (isDebugMode) {
                console.log('Straddle: Setting src for iframe:', iframe);
              }
              const src = iframe.getAttribute('data-straddle-src') || '';
              iframe.src = src;
            }
          }
        }
      } catch (error) {
        console.error('Straddle: Failed to initialize embeds. Error:', error);
      }
    };

    // Check if the Straddle script is already loaded
    if (!window.Straddle && !document.querySelector(`script[src="${workerUrl}"]`)) {
      const script = document.createElement('script');
      script.src = workerUrl;
      script.async = true;
      script.onload = initStraddleEmbed;
      script.onerror = () => {
        console.error('Failed to load the Straddle embed script.');
        initStraddleEmbed(); // Fallback in case of error
      };
      document.body.appendChild(script);
    } else {
      // Initialize immediately if Straddle is available
      initStraddleEmbed();
    }
  })();
</script>

Note: Replace {organization_id} with your client’s actual organization ID obtained from the API response.

How It Works

  • Iframe Setup: The iframe uses the data-straddle-src attribute to hold the embed URL, including your client’s organization_id. The src attribute is initially omitted to prevent immediate loading.

  • Initialization Script: The script checks for the presence of the Straddle script and loads it if necessary. It then initializes the embeds by setting the src attribute of each iframe.

  • Automatic Loading: This method is ideal when you want the embed to load automatically without any additional code or user interaction.


Approach 2: Dynamic Loading

For greater control over when the embed loads, use the Dynamic Loading approach. This method allows you to decide exactly when to initialize the embeds by calling Straddle.loadEmbeds().

Example Usage

Step 1: Include the Straddle Embed Initialization Script
<script>
  (function (global) {
    'use strict';
    // Initialize the Straddle object if it doesn't already exist
    global.Straddle = global.Straddle || {};

    // Define the loadEmbeds function
    global.Straddle.loadEmbeds = function () {
      try {
        const isDebugMode = false; // Set to true for debugging

        if (isDebugMode) {
          console.log('Straddle: Loading embeds...');
        }

        const iframes = document.querySelectorAll(
          'iframe[data-straddle-src]:not([src])'
        );

        // Check if NodeList.forEach is available
        if (typeof iframes.forEach === 'function') {
          iframes.forEach((iframe) => {
            if (isDebugMode) {
              console.log('Straddle: Setting src for iframe:', iframe);
            }
            const src =
              iframe.dataset?.straddleSrc ||
              iframe.getAttribute('data-straddle-src') ||
              '';
            iframe.src = src;
          });
        } else {
          // Fallback for older browsers
          for (let i = 0; i < iframes.length; i++) {
            const iframe = iframes[i];
            if (isDebugMode) {
              console.log('Straddle: Setting src for iframe:', iframe);
            }
            const src = iframe.getAttribute('data-straddle-src') || '';
            iframe.src = src;
          }
        }
      } catch (error) {
        console.error('Straddle: Failed to load embeds. Error:', error);
      }
    };
  })(window);
</script>
Step 2: Add the Straddle Embed Iframe
<iframe
  data-straddle-src="https://go.straddle.io/account?alignLeft=1&hideTitle=1&transparentBackground=1&dynamicHeight=1&embed=1&org={organization_id}"
  loading="lazy"
  width="100%"
  height="500"
  frameborder="0"
  title="Activate your Straddle account"
></iframe>

Note: Replace {organization_id} with your client’s actual organization ID.

Step 3: Load Embeds Dynamically

Call the Straddle.loadEmbeds() function at the point in your code where you want the embeds to load.

Option A: Load on Page Load

<script>
  document.addEventListener('DOMContentLoaded', function () {
    // Load the embeds when the DOM is fully loaded
    if (window.Straddle && typeof window.Straddle.loadEmbeds === 'function') {
      window.Straddle.loadEmbeds();
    } else {
      console.error('Straddle: loadEmbeds function is not available.');
    }
  });
</script>

Option B: Load on User Interaction

<button id="loadEmbedButton">Activate Account</button>

<script>
  document.getElementById('loadEmbedButton').addEventListener('click', function () {
    // Load the embeds when the button is clicked
    if (window.Straddle && typeof window.Straddle.loadEmbeds === 'function') {
      window.Straddle.loadEmbeds();
    } else {
      console.error('Straddle: loadEmbeds function is not available.');
    }
  });
</script>

How It Works

  • Initialization Script:

    • Defines a global Straddle object if it doesn’t already exist.

    • Adds a loadEmbeds method that sets the src attribute of all iframes with data-straddle-src, triggering the embeds to load.

    • Includes compatibility checks for older browsers and uses strict mode.

  • Manual Control:

    • You decide when to call Straddle.loadEmbeds(), giving you flexibility to load embeds based on user actions or specific conditions in your platform.
  • Embed Loading:

    • The loadEmbeds function processes all relevant iframes, ensuring they load correctly across different browsers.

Approach 3: React Integration

For platforms built with React, this approach demonstrates how to integrate Straddle Embed within a React component, giving you dynamic control over the embedding process.

Example Usage

import React, { useEffect } from 'react';

const StraddleEmbedComponent = ({ organizationId }) => {
  useEffect(() => {
    const embedScriptSrc = 'https://forms.straddle.io/embed.js';
    const isDebugMode = false; // Set to true for debugging

    const loadEmbeds = () => {
      try {
        if (window.Straddle && typeof window.Straddle.loadEmbeds === 'function') {
          // Load embeds using the Straddle script
          window.Straddle.loadEmbeds();
        } else {
          // Fallback: Manually set iframe src attributes
          const iframes = document.querySelectorAll(
            'iframe[data-straddle-src]:not([src])'
          );

          // Check if NodeList.forEach is available
          if (typeof iframes.forEach === 'function') {
            iframes.forEach((iframe) => {
              if (isDebugMode) {
                console.log('Straddle: Setting src for iframe:', iframe);
              }
              const src =
                iframe.dataset?.straddleSrc ||
                iframe.getAttribute('data-straddle-src') ||
                '';
              iframe.src = src;
            });
          } else {
            // Fallback for older browsers
            for (let i = 0; i < iframes.length; i++) {
              const iframe = iframes[i];
              if (isDebugMode) {
                console.log('Straddle: Setting src for iframe:', iframe);
              }
              const src = iframe.getAttribute('data-straddle-src') || '';
              iframe.src = src;
            }
          }
        }
      } catch (error) {
        console.error('Straddle: Failed to load embeds. Error:', error);
      }
    };

    const existingScript = document.querySelector(
      `script[src="${embedScriptSrc}"]`
    );

    const handleScriptError = () => {
      console.error('Failed to load the Straddle embed script.');
      loadEmbeds(); // Fallback in case of error
    };

    if (window.Straddle && typeof window.Straddle.loadEmbeds === 'function') {
      // Straddle script is already loaded
      loadEmbeds();
    } else if (!existingScript) {
      // Script is not in the DOM, create it
      const script = document.createElement('script');
      script.src = embedScriptSrc;
      script.async = true;
      script.onload = loadEmbeds;
      script.onerror = handleScriptError;
      document.body.appendChild(script);
    } else {
      // Script is in the DOM but may not have loaded yet
      existingScript.addEventListener('load', loadEmbeds);
      existingScript.addEventListener('error', handleScriptError);
    }

    // Cleanup function to remove event listeners
    return () => {
      if (existingScript) {
        existingScript.removeEventListener('load', loadEmbeds);
        existingScript.removeEventListener('error', handleScriptError);
      }
    };
  }, [organizationId]); // Re-run effect if organizationId changes

  return (
    <div>
      <iframe
        data-straddle-src={`https://go.straddle.io/account?alignLeft=1&hideTitle=1&transparentBackground=1&dynamicHeight=1&embed=1&org=${organizationId}`}
        loading="lazy"
        width="100%"
        height="500"
        frameBorder="0"
        title="Activate your Straddle account"
      ></iframe>
    </div>
  );
};

export default StraddleEmbedComponent;

Usage Example

import React from 'react';
import StraddleEmbedComponent from './StraddleEmbedComponent';

const App = () => {
  const organizationId = 'your-organization-id'; // Replace with your client's actual ID

  return (
    <div>
      <h1>Welcome to Our Service</h1>
      <StraddleEmbedComponent organizationId={organizationId} />
    </div>
  );
};

export default App;

How It Works

  • Component Initialization: The useEffect hook ensures the embed script is loaded when the component mounts.

  • Script Loading:

    • Checks if the Straddle script is already present.

    • If not, it dynamically adds the script to the document.

    • Adds event listeners to handle the script’s load and error events.

  • Embed Loading: Calls loadEmbeds() to initialize the embeds once the script is loaded.

  • Cleanup: Removes event listeners when the component unmounts to prevent memory leaks.

Best Practices

  • Script Placement: Always include the embed initialization script before attempting to load the embeds.

  • Replace Placeholders: Ensure you replace {organization_id} with your client’s actual organization ID in the iframe data-straddle-src attribute.

  • Control Loading: Use the Manual Loading approach if you need to load the embed after specific conditions are met.

  • Error Handling: Monitor the console for error messages to troubleshoot any issues during development.

  • Browser Compatibility:

    • If supporting older browsers, ensure your code is compatible or use polyfills where necessary.

    • The provided code includes fallbacks for features like NodeList.forEach and dataset.

  • Security Considerations:

    • Sanitize any dynamic data used in URLs to prevent injection attacks.

    • Ensure that organizationId values are validated.

  • Performance Optimization:

    • Load the embed script asynchronously to prevent blocking page rendering.

    • Consider lazy loading embeds when they are needed to improve initial load times.

  • Debugging:

    • Use the isDebugMode flag to enable or disable detailed logging during development.

Notes

  • Embed Script URL: The Straddle embed script is available at https://forms.straddle.io/embed.js.

  • Iframe Customization:

    • Adjust URL parameters (alignLeft, hideTitle, transparentBackground, etc.) to customize the form’s appearance.

    • Set iframe attributes (width, height, title) as needed for your layout.

Appendix: Error Handling and Debugging

  • Logging:

    • The scripts include console.error statements to assist in debugging.

    • Use the isDebugMode flag to enable console.log statements during development.

    • Set isDebugMode to false in production to avoid cluttering the console.

  • Error Messages:

    • The scripts provide detailed error messages to help troubleshoot issues.

    • For example, "Straddle: Failed to load embeds. Error:" followed by the error details.

  • Fallback Mechanisms:

    • The code includes fallbacks to ensure that if the Straddle script fails to load, the embeds are still initialized manually.

    • In the React example, the loadEmbeds function is called even if the script fails to load, attempting to load the embeds manually.

  • Browser Compatibility:

    • The code includes checks and fallbacks for features not supported in older browsers (e.g., NodeList.forEach, dataset).

Final Remarks

By following this guide and using the provided code snippets, you should be able to integrate Straddle forms into your platform smoothly, allowing you to onboard your clients efficiently. Whether you need a quick embed solution, manual control over loading, or integration within a React application, Straddle provides the flexibility to meet your development needs.

Remember to:

  • Replace placeholder values with your actual data.

  • Handle errors appropriately and monitor console messages during development.

  • Test your integration thoroughly to ensure the best experience for your clients.