web建站教程
  1. 首页
  2. vuejs
  3. js
  4. 好玩
  5. seo教程
  6. 前端知识
  7. 百度echarts
  8. 更多
    php入门
    nodejs
    mockjs
    reactjs
    mysql
    wordpress
    织梦cms
    帝国cms
    git教程
    IT知识
    模板大全
    休息站

localStorage如何实现记住浏览记录

585 ℃
     

localStorage如何实现记住浏览记录,我这里使用的 localStorage,数据完全保存在浏览器中,不会有影响服务器响应, 但是在 IE6/7 中不能使用!

1、建一个viewhistory.js

ViewHistory = function() {
    this.config = {
        limit: 10,
        storageKey: 'viewHistory',
        primaryKey: 'url'
    };
    this.cache = {
        localStorage:  null,
        userData:  null,
        attr:  null
    };
};
ViewHistory.prototype = {
    init: function(config) {
        this.config = config || this.config;
        var _self = this;
        if (!window.localStorage && (this.cache.userData = document.body) && this.cache.userData.addBehavior && this.cache.userData.addBehavior('#default#userdata')) {
            this.cache.userData.load((this.cache.attr = 'localStorage'));
            this.cache.localStorage = {
                'getItem': function(key) {
                    return _self.cache.userData.getAttribute(key);
                },
                'setItem': function(key, value) {
                    _self.cache.userData.setAttribute(key, value);
                    _self.cache.userData.save(_self.cache.attr);
                }
            };
        } else {
            this.cache.localStorage = window.localStorage;
        }
    },
    addHistory: function(item) {
        var items = this.getHistories();
        for(var i=0, len=items.length; i<len; i++) {
            if(item[this.config.primaryKey] && items[i][this.config.primaryKey] && item[this.config.primaryKey] === items[i][this.config.primaryKey]) {
                items.splice(i, 1);
                break;
            }
        }
        items.push(item);
        if(this.config.limit > 0 && items.length > this.config.limit) {
            items.splice(0, 1);
        }
        var json = JSON.stringify(items);
        this.cache.localStorage.setItem(this.config.storageKey, json);
    },
    getHistories: function() {
        var history = this.cache.localStorage.getItem(this.config.storageKey);
        if(history) {
            return JSON.parse(history);
        }
        return [];
    }
};
function historyList(config){
    if(typeof localStorage !== 'undefined' && typeof JSON !== 'undefined') {
        var viewHistory = new ViewHistory();
        viewHistory.init({
            limit: config.limit,
            storageKey: config.storageKey,
            primaryKey: config.primaryKey
        });
    }
    // 如果
    var wrap = document.getElementById(config.storageKey);
    if(!viewHistory){
        if(wrap){
            wrap.style.display = 'none';
        }
        return;
    }
    // 如果 ViewHistory 的实例存在,并且外层节点存在,则可显示历史浏览记录
    if(viewHistory && wrap) {
           // 获取浏览记录
        var histories = viewHistory.getHistories();
            // 组装列表
        var list = document.createElement('ul');
        if(histories && histories.length > 0) {
            for(var i=histories.length-1; i>=0; i--) {
                var history = histories[i];
                var item = document.createElement('li');
                var link = document.createElement('a');
                link.href = history.url;
                link.innerHTML = history.title;
                item.appendChild(link);
                list.appendChild(item);
            }
            // 插入页面特定位置
            wrap.appendChild(list);
        }
    }
    if( viewHistory && config.addHistory) {
        var page = {
            "title": document.getElementsByTagName('title')[0].innerHTML.split(config.titleSplit)[0],
            // 这里需要注意把标题的class名替换掉
            "url": location.href // 这是 primaryKey
            // "time": ...
            // "author": ...
            // 这里可以写入更多相关内容作为浏览记录中的信息
        };
        viewHistory.addHistory(page);
    }
}

2、在需要添加显示历史记录的地方添加:

<div id="historyList" >
  <h3>您刚刚看过如下文章:</h3>
</div>

3、调用脚本方法:

<script>
historyList({
    limit: 5,
    storageKey: 'historyList',
    primaryKey: 'url',
    addHistory:  true;
    titleSplit: '|'
});
</script>

limit 用于记录显示的条数和存储的条数,可自行修改条数
storyageKey 用于配置需要显示的id,也代表着localStorage保存这些历史记录的为一个值
primaryKey 用户表示存储字段中以什么字段作为数据唯一的判断(一般以url)
addHistory 是否添加历史记录,一般主页不需要保存,而文章页需要保存

如果你用的是 typecho 那可以用下面逻辑判断:
addHistory: <?php if ($this->is('post')) { ?> true <?php }else{ ?>false<?php } ?>,
titleSplit用于表示标题以什么作为切割,切割之后取第一截。

纯前端有哪些方法可以实现缓存

前端如何利用localStorage方法写入/读取缓存

html5标签中有哪些离线存储方式

vue开发如何实现数据缓存

sessionStorage和localStorage基本操作方法介绍

标签: localStorage, 历史记录, 浏览器存储

上面是“localStorage如何实现记住浏览记录”的全面内容,想了解更多关于 前端知识 内容,请继续关注web建站教程。

当前网址:https://ipkd.cn/webs_2096.html

声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

当前位置: 网站首页 > 前端知识
本文共计3541个字,预计阅读时长24分钟
生活小工具,收录了80多款小工具
上一篇: 抖音联合方正打造免费可商用品牌字体——抖音美好体
下一篇: 推荐一个在线图文转视频、AI 数字人工具——一帧秒创(免费赠送100分钟)
x 打工人ai神器