如何使用Node.js获取用户在网页上停留的时间?
介绍
随着互联网用户呈指数级增长,企业了解用户如何与其网站互动非常重要,以便相应地改善用户体验。
本文将探讨如何使用简单的 JavaScript 和 Node.js 获取用户在网页上停留的时间。首先,我们将尝试理解其背后的概念和原理,然后再用代码实现它。
在职的
在深入研究代码之前,让我们借助下面的流程图来了解其背后的工作原理。
执行
让我们开始动手写代码吧。
1)创建项目文件夹。
mkdir time-spent-by-user && cd time-spent-by-user
2)在文件夹中初始化 npm。
npm init -y
3)安装所需的依赖项。
npm install --save express
npm install --save ejs
4)创建一个名为“app.js”的文件,并在其中编写一些代码。
//app.js
const express = require('express');
const ejs = require('ejs');
const bodyParser= require('body-parser');
const app = express()
const port = 80
app.set('view engine', 'ejs');
app.use(bodyParser.json());
var analytics = {};
// It will render home page
app.get('/', (req, res) => {
res.render('index');
})
// ------------------------
// It will render dashboard page
app.get('/dashboard', (req, res) => {
res.render('dashboard', {"analytics": analytics});
})
// ------------------------
// It will catch the data sent from "sendBeacon" method on home page
app.post('/updatetimespentonpage', bodyParser.text(), function(req,res){
var body = JSON.parse(req.body)
analytics[body["uid"]] = (analytics[body["uid"]]) ? (analytics[body["uid"]] + body["timeSpentOnPage"]) : (body["timeSpentOnPage"]);
res.send({"status": "done"});
});
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`)
})
5)创建一个名为“views”的文件夹。
mkdir views && cd views
6) 在 views 文件夹中创建一个名为“index.ejs”的文件,并在其中编写一些代码。
<!--index.ejs-->
<html>
<head>
<title>Home page</title>
</head>
<body>
User Id: <span id="uid"></span> </br>
Time spent on this page: <span id="time-spent">0s</span>
</body>
<script type="text/javascript">
// Check if uid already exist in cookie.
if (!getCookie("uid")) {
// if not, then create a new uid and store it in cookie.
document.cookie = "uid=U" + (Date.now().toString(36)).toUpperCase() + "; expires=Thu, 18 Dec 2030 12:00:00 UTC; path=/";
}
// -------------------------------------------
document.getElementById('uid').innerHTML = getCookie("uid");
// This setInterval function increment the value of "timeSpent" variable each second.
var timeSpent = 0;
var timeSpentInterval = setInterval(
function() {
timeSpent++;
document.getElementById('time-spent').innerHTML = timeSpent + "s";
}, 1000);
// ---------------------------------------------
// The beforeunload event triggers right before unloading of the window has begun
window.addEventListener("beforeunload", function() {
// When user close or refresh the web page, sendBeacon method asynchronously sends a small amount of data over HTTP to a web server.
navigator.sendBeacon('http://localhost/updatetimespentonpage', JSON.stringify({
uid: getCookie("uid"),
timeSpentOnPage: timeSpent
}))
});
// ---------------------------------------------
// Method used to get cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
// -----------------------------------
</script>
</html>
7) 创建“dashboard.ejs”文件并在其中编写一些代码。
<!--dashboard.ejs-->
<html>
<head>
<title>Dashboard</title>
<style type="text/css">
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 10px;
}
</style>
</head>
<body>
<h2>Dashboard</h2>
<table>
<tr>
<th>User Id</th>
<th>Time Spent</th>
</tr>
<%
var total_time_spent = 0
for(i in analytics)
{
%>
<tr>
<td><%= i %></td>
<td><%= analytics[i] %>s</td>
</tr>
<%
total_time_spent = total_time_spent + analytics[i];
}
%>
<tr>
<%
if(Object.keys(analytics).length>0){
%>
<th>Total Users: <%= Object.keys(analytics).length %></th>
<th>Avg Time Spent: <%= (total_time_spent/Object.keys(analytics).length).toFixed(2) %>s</th>
<%
}
else{
%>
<td>NA</td>
<td>NA</td>
<%
}
%>
</tr>
</table>
</body>
</html>
8)执行“app.js”文件。
//if you are inside the views folder
cd ..
node app.js
9) 打开浏览器并访问http://localhost,它将显示“UID”以及您在网页上花费的时间。
10) 现在,关闭浏览器标签页,然后访问http://localhost/dashboard
11) 在这里您可以查看所有用户及其在页面上花费的时间列表。
结论
当用户关闭或刷新主页时,会触发“beforeunload”事件,并让“sendBeacon”方法异步地将用户停留时间数据发送到服务器。服务器接收数据并将其存储在一个变量中(也可以使用传统的数据库)。
sendBeacon 旨在用于向 Web 服务器发送分析数据,并避免了传统分析数据发送技术(例如使用 XMLHttpRequest)的一些问题。点击此处了解更多信息。
如果您想获取示例实现,请查看GitHub代码。
更多最新消息,请在推特上关注我。
文章来源:https://dev.to/kalpitrathore/how-to-get-time-spent-by-users-on-a-webpage-using-node-js-530f
