利用sessionStorage收集用户访问信息,然后传递给后端

这里只是简单的收集用户的停留时间、页面加载时间、当前页面URL及来源页面,以做示例

html 复制代码
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>测试sessionStorage存储用户访问信息</title>
    </head>
    <body>
        <button id="timer">停止</button>
        <script type="text/javascript">
        //日期+时间函数
            function formatDate(){
                let date=new Date();
                let Y=date.getFullYear()+'-';
                let M=date.getMonth()+1 < 10 ? '0'+date.getMonth()+1 : date.getMonth()+1+'-';
                let D=date.getDate() < 10 ? '0'+date.getDate()+' ' : date.getDate()+' ';
                let h=date.getHours() <10 ? '0'+date.getHours()+':':date.getHours()+':';
                let m=date.getMinutes()<10 ? '0'+date.getMinutes()+":":date.getMinutes()+":";
                let s=date.getSeconds()<10 ? '0'+date.getSeconds() : date.getSeconds();
                return Y+M+D+h+m+s;
            }
            //停留时间变量
            let timer=null,
                startTime=new Date().valueOf();//开始时间
                //页面加载完成后,收集用户信息
            document.addEventListener('DOMContentLoaded',function(){
                sessionStorage.setItem('visitedPage',window.location.href);//当前页面
                sessionStorage.setItem('referrer',document.referrer);//访问来源
                sessionStorage.setItem('visitTime',formatDate());//访问的日期和时间
                //计时变量
                let seconds=0;
                timer=setInterval(function(){
                    seconds++;
                    sessionStorage.setItem('timerDisplay',seconds);//停留时间,每秒种seconds增加1
                },1000);
                
            });
            
            //这里是以点击按钮,然后把数据传递给后端;
            //现实生成过程过应该是以用户关闭页面;然后把收集数据传递给后端,用unload事件完成
            const btn=document.getElementById('timer');
            btn.addEventListener('click',function(){
                console.log(sessionStorage.getItem('timerDisplay'));
                console.log(sessionStorage.getItem('visitTime'));
                //取消停留时间变量
                clearInterval(timer);
                //将收集所有数据,存储进frondEndData对象中
                let v=sessionStorage.getItem('visitTime');
                let r=sessionStorage.getItem('referrer');
                let l=sessionStorage.getItem('loadTime');
                let d=sessionStorage.getItem('timerDisplay');
                const frontEndData={
                    visitTime:v,
                    referrer:r,
                    loadTime:l,
                    timerDisplay:d
                };
                //转换为json格式
                const frontData=JSON.stringify(frontEndData);
                const jsonHeaders=new Headers({
                    'Content-Type':'application/json'
                });
                //利用fetch传递给后端
                fetch('sessionStorage.php',{
                    method:'post',
                    body:frontData,
                    headers:jsonHeaders
                })
                .then((response)=>{
                    if(response.ok && response.status===200)
                    {
                        return response.text();
                    }
                    throw new Error('返回数据有误');
                })
                //后端返回的信息
                .then((data)=>{
                    /*
                    let result=JSON.stringify(data);
                    let res=JSON.parse(result);
                    console.log(res.msg);
                    */
                   console.log(data);
                })
                .catch(e=>{
                    console.log('连接服务器发生错误',e);
                })
                
                //将停留计时器删除
                sessionStorage.removeItem('timerDisplay');
            });

			//这里是加载完成各类要素如:CSS、图片、javascript等
			//计算加载页面共用时间;也可以用performance API里面的navigation来计算页面加载时间更精确,可以达到毫秒级
            window.addEventListener('load',function(){
                let endTime=new Date().valueOf();
                let loadTime=endTime-startTime;
                sessionStorage.setItem('loadTime',loadTime);
            });

            
            
        </script>
    </body>
</html>

后端接收文件

php 复制代码
if($_SERVER['REQUEST_METHOD']==='POST')
{
    $data=file_get_contents('php://input');
    $result=json_decode($data);
    echo $result->timerDisplay;
}
相关推荐
ai小鬼头1 小时前
百度秒搭发布:无代码编程如何让普通人轻松打造AI应用?
前端·后端·github
漂流瓶jz1 小时前
清除浮动/避开margin折叠:前端CSS中BFC的特点与限制
前端·css·面试
前端 贾公子1 小时前
在移动端使用 Tailwind CSS (uniapp)
前端·uni-app
散步去海边1 小时前
Cursor 进阶使用教程
前端·ai编程·cursor
清幽竹客1 小时前
vue-30(理解 Nuxt.js 目录结构)
前端·javascript·vue.js
weiweiweb8881 小时前
cesium加载Draco几何压缩数据
前端·javascript·vue.js
幼儿园技术家1 小时前
微信小店与微信小程序简单集成指南
前端
我不吃饼干9 天前
鸽了六年的某大厂面试题:你会手写一个模板引擎吗?
前端·javascript·面试
涵信9 天前
第一节 布局与盒模型-Flex与Grid布局对比
前端·css
我不吃饼干9 天前
鸽了六年的某大厂面试题:手写 Vue 模板编译(解析篇)
前端·javascript·面试