advertisement banner show only once in browser session

扶醉桌前 提交于 2019-12-24 16:29:50

问题


How do you show an advertisement banner only once during a browser session using JavaScript or jQuery in a website? Once the session is closed and the browser is closed, the ad must be shown again when I open the website in the browser again. One more thing when i navigate across website banner must display unless it is not closed.


回答1:


You can use cookie to remember if ad was displayed or not.

You can use this plugin: https://github.com/carhartl/jquery-cookie

Make a method to display the ad:

showAd() {
 // cookie not set, display the ad and set the cookie
 if($.cookie('adDisplayed') === 'undefined') {
   // code to display the add
   // .....
   // set cookie
   $.cookie('adDisplayed', '1', { expires: 7 }); // set the cookie

 }
} 

To destroy the cookie when user leaves the page, bind beforeunload event

$(window).bind("beforeunload", function() { 
    $.removeCookie('adDisplayed'); 
})



回答2:


Use sessionStorage

The sessionStorage property allows you to access a session Storage object. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores.

Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

var banner = document.getElementById('banner');
if (sessionStorage.getItem('set') === 'set') {
  banner.style.display = 'none';
} else {
  sessionStorage.setItem('set', 'set');
}
#banner {
  width: 320;
  height: 50px;
  background: green;
  text-align: center;
}
<div id="banner">Banner</div>

Fiddle Demo




回答3:


You can play with fadeIn() and fadeOut() methods explained here

like this :

var myVar = setInterval(myTimer, 1000);

function myTimer() {
    $("#banner").fadeOut();
}

https://jsfiddle.net/bc8jgoga/




回答4:


You can set a cookie with JavaScript to remember the visit.

Example

<div id="banner"></div>
<script>
  if(typeof $.cookie("banner") === 'undefined' || $.cookie("banner") != "1") {
      $("#banner").html("My Banner");
      $.cookie("banner", "1");
  }
  window.addEventListener("beforeunload", function (e) {
      $.removeCookie("banner");
  });
</script>


来源:https://stackoverflow.com/questions/38168728/advertisement-banner-show-only-once-in-browser-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!