# TimeMe.js
**Repository Path**: Naij66/TimeMe.js
## Basic Information
- **Project Name**: TimeMe.js
- **Description**: 一个JavaScript库可用于准确计时用户浏览当前网页的时间,而无需考虑空闲时间(用户停止交互)和最小化标签或切换窗口的时间。
- **Primary Language**: JavaScript
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 1
- **Created**: 2021-03-04
- **Last Updated**: 2021-03-04
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# 项目来源为github,此处为转载,如需学习、了解更多知识,请访问源地址。
[源地址](https://github.com/jasonzissman/TimeMe.js)
```
https://github.com/jasonzissman/TimeMe.js
```
# 什么是 TimeMe.js?
TimeMe.js是一个JavaScript库,可以准确跟踪用户与网页互动的时间。 如果用户最小化浏览器或切换到其他选项卡,它将忽略在网页上花费的时间。 TimeMe.js还忽略了“空闲”时间:如果用户在可自定义的时间内闲置(无鼠标移动,无键盘输入),TimeMe.js将停止跟踪。 这些属性一起可以更准确地表示用户实际使用网页的时间。
# 什么是 TimeMe.js?
TimeMe.js是一个JavaScript库,可以准确跟踪用户与网页互动的时间。 如果用户最小化浏览器或切换到其他选项卡,它将忽略在网页上花费的时间。 TimeMe.js还忽略了“空闲”时间:如果用户在可自定义的时间内闲置(无鼠标移动,无键盘输入),TimeMe.js将停止跟踪。 这些属性一起可以更准确地表示用户实际使用网页的时间。
# 演示 Demo
你可以通过 看TimeMe.js的演示 demo.
# 如何使用 TimeMe.js?
首先,获取timeme.js的副本。 缩小版本作为timeme.min.js捆绑在此存储库中。 另外,您可以通过npm安装TimeMe.js来获得副本:
npm install timeme.js --save
下载后,只需在页面中包含以下代码行:
请注意,该代码示例将空闲持续时间设置为30秒,这意味着30秒的用户不活动(页面上没有鼠标或键盘的使用)将停止计时器。 另外,我们定义一个页面名称(“ my-home-page”)以与当前计时器关联。
*注意*: 您可以使用TimeMe.js来计时所需的任何活动,而不仅仅是页面时间。 只需围绕感兴趣的活动调用以下代码。 在查看另一个选项卡或应用程序时,TimeMe.js将自动打折任何空闲时间或空闲时间。
TimeMe.startTimer("my-activity");
// ... some time later
TimeMe.stopTimer("my-activity");
let timeOnActivity = TimeMe.getTimeOnPageInSeconds("my-activity")
当用户与您的页面互动一段时间后,TimeMe为您提供了执行功能的钩子。 只需调用`TimeMe.callAfterTimeElapsedInSeconds()`:
TimeMe.callAfterTimeElapsedInSeconds(15, function(){
console.log("The user has been actively using the page for 15 seconds! Let's prompt them with something.");
});
当用户离开页面时(由于切换标签,不活动等),TimeMe还允许您执行代码,并在用户返回页面时执行代码:
// Executes the first 5 times a user leaves the page
TimeMe.callWhenUserLeaves(function(){
console.log("The user is not currently viewing the page!");
}, 5);
// Executes every time a user returns
TimeMe.callWhenUserReturns(function(){
console.log("The user has come back!");
});
TimeMe还使您可以跟踪用户与特定元素进行交互的时间。 如果用户将鼠标移到元素(或其子元素)上,单击或键入,TimeMe将开始跟踪该交互。 多个计时器可以同时运行,因此这不会影响您已设置的其他时间。
// Start tracking activity on element with id 'area-of-interest-1'
TimeMe.trackTimeOnElement('area-of-interest-1');
// some time later...
let timeSpentOnElement = TimeMe.getTimeOnElementInSeconds('area-of-interest-1');
# 我跟踪的时间该怎么办?
在大多数情况下,您将需要存储在页面上的时间用于分析目的。 您可能需要将花费在页面上的时间发送到后端服务器。
## 通过 WebSockets 来发送时间
TimeMe.js has websocket reporting built into it. Your page will establish a websocket connection with your websocket server. TimeMe will end the connection and report the user's time when the user leaves. Simply provide a few arguments to the initialize() method to enable it:
TimeMe.initialize({
currentPageName: "my-home-page", // current page
idleTimeoutInSeconds: 30, // seconds
websocketOptions: { // optional
websocketHost: "ws://your_host:your_port",
appId: "insert-your-made-up-app-id"
}
});
## Using standard http requests to send time
Alternatively you can issue an HTTP request to your back end server to report time. *Note*: the following example sends an HTTP request during the the `window.onbeforeunload` event. This approach may not work in all browsers as there is no guarantee that the request will complete before the browser terminates it.
window.onbeforeunload = function (event) {
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","ENTER_URL_HERE", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
let timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
xmlhttp.send(timeSpentOnPage);
};
Using `onbeforeunload` is by no means a requirement. You can hook into any other event or logical point in your application to send the time spent information to the server.
If using a Single Page Application (SPA) design, TimeMe.js can have its timer stopped, page name switched, and the timer resumed (for the new page) with the following calls:
TimeMe.stopTimer();
// ... Now might be a good time to upload the time spent on the page to your server!
// ... load up new page
TimeMe.setCurrentPageName("new-page-name");
TimeMe.startTimer();
All page times are tracked in TimeMe.js, so you can review total aggregate time spent on each page for a particular user's session:
let timeSpentReport = TimeMe.getTimeOnAllPagesInSeconds();
This call will return an array of objects of page names and the corresponding aggregate
time spent on that page.
# What browsers are supported?
All major desktop and mobile browsers.
# How do I run the unit tests?
You'll need to install QUnit, which should be packaged with TimeMe.js if you performed a Bower install of TimeMe.js. Once you have installed QUnit, you can simply open the test HTML files in a browser to execute the tests.
# API
### `TimeMe.initialize(options);`
// options.currentPageName // - Optional. Name of the page (home, about, etc.).
// options.idleTimeoutInSeconds // - Optional. How long before user is considered idle. Default is 30s.
// options.initialStartTime // - Optional. Indicates start time for timer manually. Must be of type Date(). Default is *now*.
// options.trackWhenUserLeavesPage // Optional. Must be type boolean. Default is true.
// options.trackWhenUserGoesIdle // Optional. Must be type boolean. Default is true.
// options.websocketOptions: { // Optional. Turn on websocket reporting.
// websocketHost: "ws://your_host:your_port",
// appId: "insert-your-made-up-app-id"
// }
Initializes and starts first timer. Should only be called when first importing the library and beginning to time page usage. All config items are optional.
### `TimeMe.getTimeOnCurrentPageInSeconds();`
Retrieves the time spent (in seconds) on the current page.
### `TimeMe.getTimeOnPageInSeconds(pageName);`
Retrieves the time spent (in seconds) on the indicated page.
### `TimeMe.callAfterTimeElapsedInSeconds(timeInSeconds, callback);`
Sets up a handler that executes after the user has spent the specified time interacting with the page.
### `TimeMe.callWhenUserLeaves(callback, [[numberOfInvocations]]);`
Sets up a handler that executes when the user is no longer interacting with the page due to inactivity, switching tabs, or switching apps. You can optionally provide numberOfInvocations to limit how many times this executes.
### `TimeMe.callWhenUserReturns(callback, [[numberOfInvocations]]);`
Sets up a handler that executes when the user returns to the page after inactivity, switching tabs, or switching apps. You can optionally provide numberOfInvocations to limit how many times this executes.
### `TimeMe.trackTimeOnElement(elementId);`
Start timing all user activity on a certain element. A timer will be created that tracks how long the user typed, clicked, moused over, or otherwised focused on this element. Must pass in the ID of the HTML element.
### `TimeMe.getTimeOnElementInSeconds(elementId);`
Retrieve the time spent by a user on a specific element. Must pass in the ID of the HTML element.
### `TimeMe.setCurrentPageName(newPageName);`
Sets the page name to be associated with any future calls to timer.
### `TimeMe.setIdleDurationInSeconds(durationInSeconds);`
Sets the time (in seconds) that a user is idle before the timer is
turned off. Set this value to -1 to disable idle time outs.
### `TimeMe.getTimeOnAllPagesInSeconds();`
Retrieves the time spent on all pages that have been recorded using TimeMe.js. Notice this only works for Single Page Applications (SPAs) where TimeMe.js is
only initialized once.
### `TimeMe.startTimer();`
Manually starts the timer for the current page. Notice this only works if the timer is currently stopped.
### `TimeMe.stopTimer();`
Manually stops the timer. Notice this only works if the timer is currently running.
### `TimeMe.resetRecordedPageTime(pageName);`
Clears the recorded time for the indicated page name.
### `TimeMe.resetAllRecordedPageTimes();`
Clears all recorded times for all pages.
# Build Tools
To minify the code, run the following:
# install babel-minify if not already available
npm install babel-minify -g
# Minify the code
minify timeme.js --out-file timeme.min.js