Screenshot 2023-07-07 at 10.41.40 AM_0.png
Cover image for joseph_appsmith

Joseph Petty Verified userVerified user

Sr. Developer Advocate

Appsmith

Building a signature capture widget with an Iframe and SignaturePad.js

Goal

  • Build a signature capture widget using custom code in an Iframe widget srcDoc field
  • Capture signatures as images, then access the image outside of the iframe

Prerequisites

  • An Appsmith Account

  • A new or existing app - where you want to add the signature capture widget

Overview

The iframe widget is like an escape hatch that leaves the low-code environment of Appsmith and allows you to write full web apps using any framework of your choice. If there's something you can't do with one of our 45+ widgets, you can probably do it in an iframe. 

For instance, although we don't have a native signature capture widget (yet), you can easily build one with just a few lines of JavaScript, and the signaturePad.js library. 

  1. Add an Iframe Widget

    Add an iframe where you want the signature capture, and paste the following code in the srcDoc field:

    <canvas id="signature-pad" width="auto" height="auto"></canvas>
    <button id="clear">Clear</button>
    <button id="save">Save</button>
    <script src="https://cdn.jsdelivr.net/npm/signature_pad@4.0.0/dist/signature_pad.umd.min.js"></script>
    <script>
      var canvas = document.getElementById("signature-pad");
      var signaturePad = new SignaturePad(canvas, {backgroundColor: 'rgb(250,250,250)'});
      document.getElementById("clear").addEventListener('click', function () {
        signaturePad.clear();
      });
      document.getElementById("save").addEventListener('click', function () {
        var dataURL = signaturePad.toDataURL();
        window.parent.postMessage({
          type: 'signature',
          data: dataURL
        }, '*');
      });
    </script>

    Note the event listener on the SAVE button that posts a message to the parent window. 

     

  2. Access the Signature Image

    Once the SAVE button is clicked, the image will be accessible at Iframe1.message.data. You can view it in a regular Image widget, or view the raw data in a Text widget. 

    SignaturePad demo
  3. Trigger an Event when saving

    You may want to save the image back to a database, or send it in an email after signing. The Iframe widget has an onMessageReceived property, where you can select which Actions to run when a message is posted from the iframe. 

    The Action selector also allows you to add callback functions, so you can chain together Actions, and do things like saving the image to Amazon S3, then saving the new URL back to a record in MySQL. 

     

Conclusion

The Iframe widget can easily be used to create custom widgets, and new interfaces to capture and display data. By adding just a few lines of code, a Signature Capture widget can be built and integrated with the rest of your app. 

Additional Resources