admin管理员组

文章数量:1420112

I am looking for a way to identify if user refreshes a page or hits F5 using Javascript (more specifically prototype Javascript library)...

I am coding an application that needs to record the number of refresh(es) or F5 on a web page for statistics purposes. A refresh or F5 in this case means the user is skipping or escaping doing his work on the page :) So the statistics helps them find how many of them are doing it :).. Kind of policing...

I am looking for a way to identify if user refreshes a page or hits F5 using Javascript (more specifically prototype Javascript library)...

I am coding an application that needs to record the number of refresh(es) or F5 on a web page for statistics purposes. A refresh or F5 in this case means the user is skipping or escaping doing his work on the page :) So the statistics helps them find how many of them are doing it :).. Kind of policing...

Share Improve this question edited Dec 15, 2019 at 12:24 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 16, 2011 at 8:37 AbhishekAbhishek 6,91022 gold badges63 silver badges79 bronze badges 1
  • 1 Does clicking in the addressbar and hitting enter count as a refresh? – Salman Arshad Commented Dec 16, 2011 at 9:25
Add a ment  | 

4 Answers 4

Reset to default 3

Put the following piece of code on each page (only then you can differ between refreshing/navigating):

var last = localStorage["lastPage"] || "",
    current = location.href;

if(last === current) { // last page is the same as this page
    // this is a refresh
]

localStorage["lastPage"] = current;

It only differs between navigating on the same domain and not doing so (i.e. going to another website and then going back to the same page counts as a refresh).

This is a much simpler solution: window.onbeforeunload

Upon loading the page, save the time-stamp into a persistent storage (either Web Storage or cookies).

Before that, check if the time-stamp was already there. Then pare the stamps as needed.

var MIN_TIME = 60e3 // 60 seconds

var key = location.href
var now = Date.now()
var previousVisit = localStorage.getItem(key) || now

localStorage.setItem(key, now)

if (now - previousVisit < MIN_TIME) {
    alert('You lazy sloth!')
}

You can check for keycode = 116 , and detect the keypress event.

本文标签: javascriptWay to know browser refresh or F5 has been hitStack Overflow