javascript 启动 Mailchimp 邪恶弹出窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20430446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Launch Mailchimp evil popup onclick
提问by Raul
Styling
造型
<link href="//cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<style type="text/css">
#mc_embed_signup{position:absolute; top:0; left:0; width:100%; height:100%; background-color:rgba(0,0,0,.8);display:none;z-index:10000; }
#mc_embed_signup form{position:fixed; top:10%; left:50%; width:50%; margin-left:-25%; font:normal 100% Helvetica,Arial,sans-serif; font-size:14px; border-radius:4px; border:none; padding:10px 20px; background-color:#fff; color:#000; text-align:left;max-height:400px;overflow-y:auto;overflow-x:hidden;}
#mc_embed_signup a.mc_embed_close{background:transparent url(http://downloads.mailchimp.com/img/closebox.png) no-repeat; display:block; height:30px; width:30px; text-indent:-999em; position:absolute; top:-10px; right:-10px; display:none; }
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
HTML
HTML
<div id="mc_embed_signup">
<form action="http://zehava.us3.list-manage2.com/subscribe/post?u=fc807e12a60c9cbaaf5f5616e&id=0707dfe742" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<h2>We want to share with you the newest ZEHAVA creations! Leave us your email address! With this occasion, ZEHAVA offers you a gift: a free recondition of your favorite jewelry.</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address <span class="asterisk">*</span>
</label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
<label for="mce-FNAME">First Name <span class="asterisk">*</span>
</label>
<input type="text" value="" name="FNAME" class="required" id="mce-FNAME">
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Last Name </label>
<input type="text" value="" name="LNAME" class="" id="mce-LNAME">
</div>
<a href="#" id="mc_embed_close" class="mc_embed_close">Close</a> <div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
Javascript
Javascript
<script type="text/javascript">
var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';
try {
var jqueryLoaded=jQuery;
jqueryLoaded=true;
} catch(err) {
var jqueryLoaded=false;
}
var head= document.getElementsByTagName('head')[0];
if (!jqueryLoaded) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
head.appendChild(script);
if (script.readyState && script.onload!==null){
script.onreadystatechange= function () {
if (this.readyState == 'complete') mce_preload_check();
}
}
}
var err_style = '';
try{
err_style = mc_custom_error_style;
} catch(e){
err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = err_style;
} else {
style.appendChild(document.createTextNode(err_style));
}
head.appendChild(style);
setTimeout('mce_preload_check();', 250);
var mce_preload_checks = 0;
function mce_preload_check(){
if (mce_preload_checks>40) return;
mce_preload_checks++;
try {
var jqueryLoaded=jQuery;
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
head.appendChild(script);
try {
var validatorLoaded=jQuery("#fake-form").validate({});
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
mce_init_form();
}
function mce_init_form(){
jQuery(document).ready( function($) {
var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){} };
var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
$("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
options = { url: 'http://mysite.us3.list-manage1.com/subscribe/post-json?u=fcsfse12a6sfsdfsfaf5f5616e&id=0707dfe742&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
beforeSubmit: function(){
$('#mce_tmp_error_msg').remove();
$('.datefield','#mc_embed_signup').each(
function(){
var txt = 'filled';
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
var bday = false;
if (fields.length == 2){
bday = true;
fields[2] = {'value':1970};//trick birthdays into having years
}
if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else {
if (/\[day\]/.test(fields[0].name)){
this.value = fields[1].value+'/'+fields[0].value+'/'+fields[2].value;
} else {
this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
}
}
});
});
$('.phonefield-us','#mc_embed_signup').each(
function(){
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
if ( fields[0].value.length != 3 || fields[1].value.length!=3 || fields[2].value.length!=4 ){
this.value = '';
} else {
this.value = 'filled';
}
});
});
return mce_validator.form();
},
success: mce_success_cb
};
$('#mc-embedded-subscribe-form').ajaxForm(options);
$('#mc_embed_signup').hide();
cks = document.cookie.split( ';' );
var show=true;
for(i=0;i<cks.length;i++){
parts = cks[i].split('=');
if( parts[0].indexOf('MCEvilPopupClosed')!= -1 ) show = false;
}
if (show){
$('#mc_embed_signup a.mc_embed_close').show();
setTimeout( function(){ $('#mc_embed_signup').fadeIn();} , 2000);
$('#mc_embed_signup a.mc_embed_close').click(function(){ mcEvilPopupClose();});
}
$(document).keydown(function(e){
if (e == null) {
keycode = event.keyCode;
} else {
keycode = e.which;
}
if(keycode == 27){
mcEvilPopupClose();
}
});
function mcEvilPopupClose(){
$('#mc_embed_signup').hide();
var now = new Date();
var expires_date = new Date( now.getTime() + 31536000000 );
document.cookie = 'MCEvilPopupClosed=yes;expires=' + expires_date.toGMTString()+';path=/';
}
});
}
function mce_success_cb(resp){
$('#mce-success-response').hide();
$('#mce-error-response').hide();
if (resp.result=="success"){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(resp.msg);
$('#mc-embedded-subscribe-form').each(function(){
this.reset();
});
} else {
var index = -1;
var msg;
try {
var parts = resp.msg.split(' - ',2);
if (parts[1]==undefined){
msg = resp.msg;
} else {
i = parseInt(parts[0]);
if (i.toString() == parts[0]){
index = parts[0];
msg = parts[1];
} else {
index = -1;
msg = resp.msg;
}
}
} catch(e){
index = -1;
msg = resp.msg;
}
try{
if (index== -1){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
} else {
err_id = 'mce_tmp_error_msg';
html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';
var input_id = '#mc_embed_signup';
var f = $(input_id);
if (ftypes[index]=='address'){
input_id = '#mce-'+fnames[index]+'-addr1';
f = $(input_id).parent().parent().get(0);
} else if (ftypes[index]=='date'){
input_id = '#mce-'+fnames[index]+'-month';
f = $(input_id).parent().parent().get(0);
} else {
input_id = '#mce-'+fnames[index];
f = $().parent(input_id).get(0);
}
if (f){
$(f).append(html);
$(input_id).focus();
} else {
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
} catch(e){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
}
</script>
The popup is set to launch automatically and the user can exit. I want to also put a link on the site to make the popup show on command. I have tried:
弹出窗口设置为自动启动,用户可以退出。我还想在网站上放一个链接,以便按命令显示弹出窗口。我努力了:
<a onclick="$('#mc_embed_signup, #mc_embed_signup a.mc_embed_close').css('display', 'block');" href="#">Newsletter</a>
and the popup is shown but doesn't seem to work properly.
What is the correct form to launch this so called evil popup when I click on a link?
并且显示了弹出窗口,但似乎无法正常工作。
当我点击链接时,启动这个所谓的邪恶弹出窗口的正确形式是什么?
回答by Leopold Kristjansson
I recently got this code from a client (that they copied from Mailchimp.com)
我最近从客户那里得到了这个代码(他们从 Mailchimp.com 复制的)
<script type="text/javascript" src="//s3.amazonaws.com/downloads.mailchimp.com/js/signup-forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"></script>
<script type="text/javascript">require(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"mc.us8.list-manage.com","uuid":"a56ce123456bdcb7974e9ea2","lid":"4esdr6bd94"}) })</script>
This is the Evil-PopUp Code and by adding this to your site you get the popup (modal window) for newsletter-signup when the page loads.
这是 Evil-PopUp 代码,通过将其添加到您的网站,您将在页面加载时获得用于通讯注册的弹出窗口(模式窗口)。
My client wanted this popup to show only when a "Sign up now" button was clicked. So this is what I did.
我的客户希望此弹出窗口仅在单击“立即注册”按钮时显示。所以这就是我所做的。
FirstI added the first script as is to the site:
首先,我将第一个脚本按原样添加到站点:
<script type="text/javascript" src="//s3.amazonaws.com/downloads.mailchimp.com/js/signup-forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"></script>
SecondI wrote a function that runs the code from the second script and attached a click event to a button with id #open-popup
其次,我编写了一个函数来运行第二个脚本中的代码,并将点击事件附加到一个带有 id #open-popup 的按钮
function showMailingPopUp() {
require(["mojo/signup-forms/Loader"], function(L) { L.start(
{"baseUrl":"mc.us8.list-manage.com","uuid":"a56ce2128001bdcb7974e9ea2","lid":"1d4c16bd94"}
) })
};
document.getElementById("open-popup").onclick = function() {showMailingPopUp()};
I thought this was it,but found out that the Mailchimp script adds a session cookie called "MCEvilPopupClosed" after the user has closed the popup for the first time. If that cookie is set you can not open the popup again (since this popup was only meant to be shown once when the user enters the page).
我以为就是这样,但发现 Mailchimp 脚本在用户第一次关闭弹出窗口后添加了一个名为“MCEvilPopupClosed”的会话 cookie。如果设置了该 cookie,您将无法再次打开弹出窗口(因为该弹出窗口仅在用户进入页面时显示一次)。
The solution to thatwas adding this code to delete the cookie when the page loads and also each time the modal close button is clicked (requires jQuery but can of course be written in vanilla Javascript if you like). EDIT:According to new comments the cookie key has changed to MCPopupClosedfrom MCEvilPopupClosed
解决方案是添加此代码以在页面加载时以及每次单击模式关闭按钮时删除 cookie(需要 jQuery,但如果您愿意,当然可以用 vanilla Javascript 编写)。编辑:根据新的评论cookie的关键已经变成MCPopupClosed从MCEvilPopupClosed
jQuery(window).load(function() {
document.cookie = "MCEvilPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
});
jQuery('body').on('click', '.mc-closeModal', function() {
document.cookie = "MCEvilPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
});
Now...the user can open and close the Evil Popup as s/he likes.
现在...用户可以随心所欲地打开和关闭 Evil Popup。
EDIT:Instead of using my code to clear the cookies you could use the solution from @rok-jakli? below. It's better/simpler then mine. Rest should be the same.
编辑:您可以使用@rok-jakli 的解决方案,而不是使用我的代码来清除 cookie?以下。它比我的更好/更简单。休息应该是一样的。
回答by Timothy Lee Russell
This is just a copy of @LeopoldKristjansson answer with the comments from @RokJakli? regarding the cookie integrated and binding the click with jQuery.
这只是@LeopoldKristjansson 回答的副本以及@RokJakli 的评论?关于 cookie 集成和绑定与 jQuery 的点击。
Javascript
Javascript
<script type="text/javascript" src="//s3.amazonaws.com/downloads.mailchimp.com/js/signup-forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"></script>
<script type="text/javascript">
function showMailingPopUp() {
require(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"obscured","uuid":"obscured","lid":"obscured"})})
document.cookie = "MCEvilPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
};
$(function() {
$(".open-popup").on('click', function() {
showMailingPopUp();
});
});
</script>
Html
html
<div class="open-popup">Open evil popup</div>
回答by plvdmeer
I needed to add "path=/" to make this work on every page, because MailChimp sets the cookie to the root domain. My website isn't using jQuery and adding it for such a small functionality isn't worth it. The cookie also wasn't called MCEvilPopupClosed for me, but MCPopupClosed.
我需要添加“path=/”才能在每个页面上都能正常工作,因为 MailChimp 将 cookie 设置为根域。我的网站没有使用 jQuery,为这么小的功能添加它是不值得的。对我来说,cookie 也不是 MCEvilPopupClosed,而是 MCPopupClosed。
Placed in Head
置于头部
<script type="text/javascript" src="//s3.amazonaws.com/downloads.mailchimp.com/js/signup-forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"></script>
<script type="text/javascript">
function showMailPopup() {
document.cookie = "MCPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
document.cookie = "MCPopupSubscribed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
require(["mojo/signup-forms/Loader"],function(L){L.start({"baseUrl":"mc.us16.list-manage.com","uuid":"8cb755a469ca9c2a6e87c6502","lid":"b809b6d15b"})});
};
</script>
Placed in Body
放置在身体
<button onclick="showMailPopup()">Click</button>
回答by Miguel Mota
Make sure to expire cookie (adding path was required for it to work on all pages):
确保 cookie 过期(需要添加路径才能在所有页面上工作):
document.cookie = "MCEvilPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
回答by Etienne Dupuis
I was forced to clear 2 cookies to make it work.
我被迫清除 2 个 cookie 以使其正常工作。
document.cookie = "MCPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
document.cookie = "MCPopupSubscribed=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
回答by Michael Cole
For the one other person who will try this with Nuxt/Vue.js (or some other system that fails when compiling the require
), here's what worked for me:
对于将使用 Nuxt/Vue.js(或编译 .js 时失败的其他系统)尝试此操作的另一个人,这对我有用require
:
```
export default {
mounted() {
this.setupMailchimpPopup()
},
methods: {
setupMailchimpPopup () {
var chimpPopupLoader = document.createElement("script");
chimpPopupLoader.src = '//s3.amazonaws.com/downloads.mailchimp.com/js/signup-forms/popup/embed.js';
chimpPopupLoader.setAttribute('data-dojo-config', 'usePlainJson: true, isDebug: false');
var m = {
baseUrl: "mc.us19.list-manage.com",
uuid: "xxx",
lid: "xxx"
};
var s = `
document.cookie = "MCPopupClosed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
document.cookie = "MCPopupSubscribed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
require(["mojo/signup-forms/Loader"], function (L) {
window._showMailchimpPopup = function() {
L.start({baseUrl: "${m.baseUrl}", uuid: "${m.uuid}", lid: "${m.lid}"});
};
});
`;
console.log(s);
var chimpPopup = document.createElement("script");
chimpPopup.appendChild(document.createTextNode(s));
chimpPopupLoader.onload = function() {
document.body.appendChild(chimpPopup);
}
document.body.appendChild(chimpPopupLoader);
},
```
Now the popup can be opened with window._showMailchimpPopup()
from Vue or etc. It won't open again on a 2nd click unless the page is reloaded.
现在可以使用window._showMailchimpPopup()
Vue 或其他工具打开弹出窗口。除非重新加载页面,否则第二次单击时它不会再次打开。