如何修改Mailchimp订阅弹窗Cookie的过期时长?
Hey there, I feel your pain—Mailchimp doesn’t expose settings for modifying the MCPopupClosed (1 year default) or MCPopupSubscribed (3 months default) cookie lifespans directly in their form builder. But with a bit of custom JavaScript, you can override these defaults easily. Here’s how to do it:
Key Background
Mailchimp’s popup script automatically sets these cookies when you close the popup or complete a subscription. Our workaround will listen for those events, delete the default cookie, and replace it with one that has your desired expiration date.
Step 1: Override MCPopupClosed Cookie (When User Closes Popup)
Add this script to your site after the Mailchimp popup embed code (preferably right before the closing </body> tag, or wrapped in a DOMContentLoaded listener):
document.addEventListener('DOMContentLoaded', function() { // Listen for the popup close event fired by Mailchimp document.addEventListener('mc-popup-close', function() { // Clear the default cookie Mailchimp sets document.cookie = "MCPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; // Set your custom expiration (example: 7 days from now) const customExpiry = new Date(); customExpiry.setDate(customExpiry.getDate() + 7); // Change "7" to your desired number of days // Create the new cookie with your settings document.cookie = `MCPopupClosed=yes; expires=${customExpiry.toUTCString()}; path=/; SameSite=Lax`; }); });
Step 2: Override MCPopupSubscribed Cookie (After Successful Subscription)
Add this script alongside the one above to adjust the cookie set when someone completes a subscription:
// Listen for the successful subscription event from Mailchimp document.addEventListener('mc-embedded-subscribe-success', function() { // Clear the default subscribed cookie document.cookie = "MCPopupSubscribed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; // Set your custom expiration (example: 30 days from now) const customExpiry = new Date(); customExpiry.setDate(customExpiry.getDate() + 30); // Adjust "30" to your preferred days // Create the new subscribed cookie document.cookie = `MCPopupSubscribed=yes; expires=${customExpiry.toUTCString()}; path=/; SameSite=Lax`; });
Important Notes
- Test first: Clear any existing Mailchimp cookies in your browser before testing, so old cookies don’t interfere with your new settings.
- Adjust expiration: Modify the number in
setDate(customExpiry.getDate() + X)to set how many days you want the cookie to last. - SameSite attribute: Keep
SameSite=Laxfor most cases (it’s a secure default), but adjust toStrictorNoneif your site requires it (note:Noneneeds theSecureattribute if using HTTPS). - Event reliability: Mailchimp’s event names are stable for now, but if they update their popup script, you might need to verify the event names via browser dev tools.
内容的提问来源于stack exchange,提问作者Henriksan

