admin管理员组

文章数量:1442858

JS 判断页面是否为首次加载

前言

需要判断一个页面是否为首次加载就需要向浏览器写入一段数据,这段数据可以作为检测依据。如果无法读取这段数据那么则认为是首次加载,能读取到数据则为二次加载。并且写入的这段数据不能因为链接改变、刷新而消失。

在 javascript 中能够符合以上条件的对象有sessionStoragewindow.name两个;第一个可以存储5M的数据,以key/value对方式存储;第二个可以存储2M的数据,每个页面都可以读写或者覆盖window.name内数据。

用法

sessionStorage

代码语言:javascript代码运行次数:0运行复制
//写入当前url
sessionStorage.setItem("url", window.location.href);

//读取
var url = sessionStorage.getItem("url");

window.name

代码语言:javascript代码运行次数:0运行复制
//写入当前url
window.name = window.location.href;

//读取
var url = window.name;

示例代码

sessionStorage

代码语言:javascript代码运行次数:0运行复制
var geturl = sessionStorage.getItem("url"),
    url = window.location.href;
if (geturl === null) {
    sessionStorage.setItem("url", url);
    console.log("首次加载");
} else if (geturl === url) {
    console.log("页面刷新");
} else {
    sessionStorage.setItem("url", url);
    console.log("你来到了一个全新的页面");
}

window.name

代码语言:javascript代码运行次数:0运行复制
var geturl = window.name,
    url = window.location.href;
if (geturl.indexOf('') === -1) {
    window.name = url;
    console.log("首次加载");
} else if (geturl === url) {
    console.log("页面刷新");
} else {
    window.name = window.location.href;
    console.log("你来到了一个全新的页面");
}

本文标签: JS 判断页面是否为首次加载