How to add a Substack Newsletter Sign-up form to a Squarespace Promotional Pop-up

Squarespace has a built-in promotional pop-up feature that is great for getting new newsletter subscribers, but it only works with the native square space mailing list, MailChimp, or Google Drive. After a whole bunch of experimenting and hair pulling, here is a fix that I developed that allows you to change the content of the square space pop-up and make it, insert your SubStack newsletter sign-up form instead. Right now this is working for me using Squarespace 7.1.

  1. Copy your substack iFrame embed code.
  2. Go here and paste it in to have a reformatted to escape out all spaces and annoying characters that can mess with the JavaScript.
  3. Copy the code below, and paste your escaped embed code where it says iFrameContent
  4. Go to Settings > Advanced > Code Injection on your Squarespace site.
  5. Paste the script into the footer so that it is executed on every page where the pop-up may appear.
<script> 
var iframeContent = 'PASTE YOUR EMBED CODE HERE';

//Changes content of pop-up based on detecting when a div with .sqs-slide-wrapper is added to the DOM then changin the HTML
  // Function to change the content of the div
function changeDivContent(newContent) {
    // Select the div with the specified classes
    var div = document.querySelector('.sqs-slice-group.group-copy.copy-layer-background');
    // Check if the div exists
    if (div) {
        // Change the HTML content of the div
        div.innerHTML = newContent;
    } else {
        // Log an error message if the div is not found
        console.error('Div with specified classes not found.');
    }
}

// Function to be executed when the new div is added
function onPopupAdded() {
  //console.log('.sqs-slide-wrapper added to the DOM');
  //alert("popup detected");
  changeDivContent(iframeContent);
  // You can add any code here that you want to execute when the div is added
}

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
  for (var mutation of mutationsList) {
    if (mutation.type === 'childList') {
      mutation.addedNodes.forEach((node) => {
        if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('sqs-slide-wrapper')) {
          // The div with the class 'sqs-slide-wrapper' was added
          onPopupAdded();
          // You might want to disconnect the observer after the div is added if it's only needed once
          observer.disconnect();
        }
      });
    }
  }
};

// Create a new observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the body of the page for changes in the child elements
observer.observe(document.body, { childList: true, subtree: true });
</script>

Enjoy!