window popup blocker issue

2019-07-31 02:23发布

问题:

I am using the below script to popup a coupon window automatically. However, Chrome and other browsers are blocking the popup, as expcected. Is there a way to avoid this from being blocked by the pop-up blocker? Also, how do I center it?

Code:

<SCRIPT LANGUAGE="JavaScript">
<!--
function GetCookie(name) {
  var arg=name+"=";
  var alen=arg.length;
  var clen=document.cookie.length;
  var i=0;
  while (i<clen) {
    var j=i+alen;
    if (document.cookie.substring(i,j)==arg)
      return "here";
    i=document.cookie.indexOf(" ",i)+1;
    if (i==0) break;
  }
  return null;
}
var visit=GetCookie("COOKIE1");
if (visit==null){
   var expire=new Date();
    window.name = "thiswin";
    newwin=open("popup.html", "dispwin",  
    "width=730,height=424,scrollbars=no,menubar=no");
   document.cookie="COOKIE1=here; expires=Thu 01-01-2004 00:00:00 GMT;";
}
// -->
</SCRIPT>

回答1:

Is there a way to avoid this from being blocked by the pop-up blocker?

Yes: Call window.open from within the event handler of a user-generated event, such as a click. This is the primary criterion browsers use when deciding whether to block a popup, as it gives at least some indication the user asked for something.


Rather than a pop-up, for something like this I would strongly recommend using a banner bar or similar. You'd have something like this in the markup at the top of the HTML:

<div id="first-time-banner" style="display: none">text here</div>

And then change the last bit of that code to:

if (visit==null){
   var expire=new Date();
   document.getElementById("first-time-banner").style.display = "block";
   document.cookie="COOKIE1=here; expires=Thu 01-01-2004 00:00:00 GMT;";
}

That will show the banner to users who don't have the cookie set yet. You'd probably want to have something in the banner that lets the user close it, which involves hooking user events on elements (a close button or similar). For instance:

<div id="first-time-banner" style="display: none">
    text here
    <span id="first-time-banner-close">X</span>
</div>

...with styling on the span to make it look nice. Then:

document.getElementById("first-time-banner-close").onclick = function() {
    document.getElementById("first-time-banner").style.display = "none";
};

(There are other ways to hook things up, but they're slightly more complicated.)



回答2:

Also to center you would do something like so:

<div id="PopUpFad" style="left: 514.5px; opacity: 0.9999899999999999; position: absolute;
 top: 50%; 
 left: 50%; 
 margin-top: -195px; 
 margin-left: -314px;" class="show"><div class="PopUpFadClose"><a href="#" onclick="PopUpFadCloseX()"><img src="http://livefitrevolution.org/wp-content/plugins/cool-fade-popup/close.jpg"></a></div><div><img src="http://livefitrevolution.org/wp-content/uploads/motivation-difference.jpg"></div></div>

Here's a fiddle for visual aid:

http://jsfiddle.net/Maikel1234/C5rRm/1/