简体   繁体   中英

How to execute Javascript alert when page loads the first time only

I am trying to execute a javascript alert, but only alert if it is the first time that browser / computer has viewed that page - or something similar to that.
How would this be done? I have written the Javascript to what I think it be similar to.

function alert() {
    alert(" Please view this is Firefox");
}
if (first time viewing this page) {
    alert();
}

I really appreciate your help

You could use the JQuery Cookie Plugin for this.

function showPopUp() {
    var cookie = $.cookie('the_cookie');
    if(!cookie){
        alert(" Please view this in Firefox");
        $.cookie('the_cookie', 'the_value');
    }
}
showPopUp();

You can use localStorage or cookies :

Here is an example with localStorage :

var visited = localStorage.getItem('visited');
if (!visited) {
  alert("Please view this is Firefox");
  localStorage.setItem('visited', true);
}

Don't use a Cookie it will be sent to the server at each time your make request. You can use Local Storage instead, like:

function load() {
  var isFired = localStorage.getItem('checkFired');

  if (isFired != '1'){
      alert(" Please view this is Firefox");
      localStorage.setItem('checkFired', '1');
  }
}
load();

Set cookie

document.cookie="first=first";

Read a Cookie with JavaScript

var x = document.cookie;

Example:

function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) 
  {
  var c = ca[i].trim();
  if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
return "";
}

function checkCookie()
{
  var first=getCookie("first");
  if(first == "first")
  {
    alert(" Please view this is Firefox");
  }else{
    document.cookie="first=first";
  }
}

Cookie in JS

看到此链接,您将获得一些基于cookie的想法示例 。一旦键入您的值,然后刷新它,它将显示该值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM