如何为TypeForm嵌入的iframe弹窗设置Cookie以阻止重复弹出?
Got it, let's fix that annoying repeated Typeform popup issue. Here's exactly how to implement the cookie-based solution Typeform support mentioned:
The core idea is to track when a user closes the popup with a cookie, then skip loading the form if that cookie exists on subsequent page visits.
Step 1: Add Cookie Helper Functions
First, throw these simple cookie utilities into your site's JavaScript (either in a <script> tag in your footer or your main JS file):
// Set a cookie to remember the user closed the form function setCookie(name, value, daysUntilExpire) { let expiryString = ""; if (daysUntilExpire) { const expiryDate = new Date(); expiryDate.setTime(expiryDate.getTime() + (daysUntilExpire * 24 * 60 * 60 * 1000)); expiryString = "; expires=" + expiryDate.toUTCString(); } document.cookie = `${name}=${value || ""}${expiryString}; path=/`; } // Check if the "form closed" cookie exists function getCookie(name) { const cookieMatch = `${name}=`; const cookieList = document.cookie.split(';'); for (let cookie of cookieList) { cookie = cookie.trim(); if (cookie.startsWith(cookieMatch)) { return cookie.substring(cookieMatch.length); } } return null; }
Step 2: Modify Your Typeform Embed Logic
Instead of loading the Typeform automatically on every page load, wrap the embed code in a cookie check. We'll also listen for the form's close event to set the cookie when the user clicks the 'X'.
Option 1: Basic Embed Script
If you're using the standard Typeform embed script:
// Only load the popup if the user hasn't closed it before if (!getCookie('typeform_has_closed')) { // Load your Typeform embed script const embedScript = document.createElement('script'); embedScript.src = 'https://embed.typeform.com/embed.js'; // Replace with your specific embed URL embedScript.async = true; document.body.appendChild(embedScript); // Listen for the form close event to set the cookie window.addEventListener('message', (event) => { if (event.data?.type === 'form-closed') { // Set cookie to hide the popup for 30 days (adjust the number as needed) setCookie('typeform_has_closed', 'true', 30); } }); }
Option 2: Typeform SDK (Cleaner)
If you're using Typeform's official SDK, use the onClose callback directly:
if (!getCookie('typeform_has_closed')) { window.tf.createPopup('YOUR_UNIQUE_FORM_ID', { onClose: () => { setCookie('typeform_has_closed', 'true', 30); } }).open(); }
Quick Notes
- Adjust the
daysUntilExpirevalue insetCookieto control how long the popup stays hidden (e.g., 7 for a week, 90 for 3 months). - Double-check that your Typeform is configured to send the
form-closedevent—most default embed setups include this, but you can verify in your Typeform embed settings.
To ensure the Typeform only appears once you will have to add cookies to your site in order to ensure a user only sees it...
— Typeform Support
内容的提问来源于stack exchange,提问作者Dave Pearce

