I am wondering if there is a way to disable an automatic page refresh when a page loses focus. I have it setup to refresh when it gains focus again already using this:
window.onblur= function() {window.onfocus= function () {location.reload(true)}};
that I found from here. I originally had the page auto refresh by using:
<meta http-equiv="refresh" content="60"/>
Which reloads the page every 60 seconds regardless of state.
I want to make the page have the auto refresh only when in focus with the initial refresh coming when the page gains focus again. After the gain of focus it should refresh at the time interval until focus is lost.
Thanks
You can't override this kind of refresh, you should probably use a JS timer to refresh, something like this (after removing the <meta http-equiv="refresh" content="60" /> tag):
var hasFocus;
window.onblur = function() {
hasFocus = false;
}
window.onfocus = function(){
hasFocus = true;
}
setInterval(reload, 60*1000);
function reload(){
if(hasFocus){
location.reload(true);
}
}
I ended up modifying the code from Mostafa Torbjørn Berg to maintain the refresh on focus and have the page automatically refresh every 60 seconds while the page has focus.
var hasFocus= true;
window.onblur = function() {
hasFocus = false;
}
window.onfocus = function(){
location.reload(true);
}
setInterval(reload, 60*1000);
function reload(){
if(hasFocus){
location.reload(true);
}
}
Related
Im attempting to log the user activity in my database when they login and logout of the site. This works fine, but when they close the page via a tab or browser, there is no way to run the logout query, so according to the records the user never logs out of the site.
Method 1:
I have tried onbeforeunload, but this does not seem to trigger before the page closes.
Method 2:
I would try the method of using an ajax keepalive token sent to the php, but this would need to run every 1 min and could cause high traffic load.
Method 3:
I was hoping an alterantive would be to set the session.gc.maxlifetime to 1 min and add a call to the logout query via a destroy session callback.
Which would be the best method, or is there a better method of achieving this?
Is there a way to trigger a custom function(query) before php destroy session or php garbage collection has taken place?
UPDATE
I have taken the advise of everyone and decided to attempt 'method 1'. So far this is my attempt but its still not working perfectly:
var isClosePage = true;
//detect f5 and backspace page navigation
$(document).on('keypress', function(e)
{
if (e.keyCode == 116)
{
alert('f5');
isClosePage = false;
}
if (e.keyCode == 8)
{
alert('backspace');
isClosePage = false;
}
});
//detect back and forward buttons
$(window).bind('statechange',function()
{
alert('back');
isClosePage = false;
});
//detect page button press
$('html').on('mouseenter', function()
{
console.log('mouse has enetered!');
isClosePage = false;
});
//detect browser buttons press
$('html').on('mouseleave', function()
{
console.log('mouse has left!');
isClosePage = true;
});
//make ajax call (logout) to server if above events not triggered
$(window).on('beforeunload', function(e)
{
if(isClosePage)
{
$.ajax(
{
url:'php/function/active-user.php?logout=ajax',
dataType: 'jsonp',
crossDomain: true,
async: false
});
//return 'some default message';
}
else
{
isClosePage = true;
}
});
Can anyone suggest any improvments to how I can make this work well?
When you speak of Method 1, you're doing it client-side, right?
The interface is window.onbeforeunload, and this is a usage example:
window.onbeforeunload = function(e) {
// call server script to log the user activity to database ...
};
The event window.onbeforeunload IS triggered before page is unloaded (tab/window/browser closed).
I would like to extend MarcoS's answer a little bit. window.onbeforeunload should work but this isn't the preferred way to set a handler for events. Since this is a property other scripts attaching to this event will overwrite your listener and your function will never get called.
The preferred way of registering to this event is as follows:
window.addEventListener('beforeunload', function (evt) {
}, false);
You could also attach a event listener to unload
window.addEventListener('unload', function (evt) {
}, false);
Hope this helps
I am making a view count system. But the problem is that whenever the person reloads the page, the view is incremented.
In order to stop it, I used a session variable.
The code is as follows:
if ($_SESSION['var'] == NULL){
$start = "UPDATE table SET views = views+1 WHERE value = $value";
$_SESSION['var'] = true;
}
If the page is refreshed, the session variable remains intact and the condition fails and nothing happens.
PROBLEM:
But if the page is closed and re-opened, the views don't increase whereas they should.
What am I doing wrong?
I have written session_start() and a PDO query to execute the function.
In order to achieve what you are looking for, you need to destroy session on browser tab/window close. Therefore you need a Ajax request that destroys the session parameter on window close.
Quoting from this article: http://eureka.ykyuen.info/2011/02/22/jquery-javascript-capture-the-browser-or-tab-closed-event/
In your web root, create the js/check_browser_close.js.
/**
* This javascript file checks for the brower/browser tab action.
* It is based on the file menstioned by Daniel Melo.
* Reference: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
*/
var validNavigation = false;
function wireUpEvents() {
/**
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*
* onbeforeunload for IE and chrome
* check http://stackoverflow.com/questions/1802930/setting-onbeforeunload-on-body-element-in-chrome-and-ie-using-jquery
*/
var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
var leave_message = 'You sure you want to leave?'
function goodbye(e) {
if (!validNavigation) {
if (dont_confirm_leave!==1) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = leave_message;
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
//return works for Chrome and Safari
return leave_message;
}
}
}
window.onbeforeunload=goodbye;
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
Also create the following .html in your web root to test the above Javascript file.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="js/check_browser_close.js"></script>
</head>
<body>
<h1>Eureka!</h1>
Google
Yahoo
Eureka!
</body>
</html>
Now you need to modify the code to call you server side file to destroy the session using Ajax.
I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was just on?
I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling.
Here's a jquery way of doing it:
jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames )
Very importantly, you'll need the jquery cookie plugin.
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When a button is clicked...
$('#submit').on("click", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
Here's still the code from the original answer:
jsfiddle
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When scrolling happens....
$(window).on("scroll", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
#Cody's answer reminded me of something important.
I only made it to check and scroll to the position vertically.
(1) Solution 1:
First, get the scroll position by JavaScript when clicking the submit button.
Second, include this scroll position value in the data submitted to PHP page.
Third, PHP code should write back this value into generated HTML as a JS variable:
<script>
var Scroll_Pos = <?php echo $Scroll_Pos; ?>;
</script>
Fourth, use JS to scroll to position specified by the JS variable 'Scroll_Pos'
(2) Solution 2:
Save the position in cookie, then use JS to scroll to the saved position when page reloaded.
Store the position in an hidden field.
<form id="myform">
<!--Bunch of inputs-->
</form>
than with jQuery store the scrollTop and scrollLeft
$("form#myform").submit(function(){
$(this).append("<input type='hidden' name='scrollTop' value='"+$(document).scrollTop()+"'>");
$(this).append("<input type='hidden' name='scrollLeft' value='"+$(document).scrollLeft()+"'>");
});
Than on next reload do a redirect or print them with PHP
$(document).ready(function(){
<?php
if(isset($_REQUEST["scrollTop"]) && isset($_REQUEST["scrollLeft"]))
echo "window.scrollTo(".$_REQUEST["scrollLeft"].",".$_REQUEST["scrollTop"].")";
?>
});
Well, if you use _targets in your code you can save that.
Or, you can do an ajax request to get the window.height.
document.body.offsetHeight;
Then drop them back, give the variable to javascript and move the page for them.
To Remember Scroll all pages Use this code
$(document).ready(function (e) {
let UrlsObj = localStorage.getItem('rememberScroll');
let ParseUrlsObj = JSON.parse(UrlsObj);
let windowUrl = window.location.href;
if (ParseUrlsObj == null) {
return false;
}
ParseUrlsObj.forEach(function (el) {
if (el.url === windowUrl) {
let getPos = el.scroll;
$(window).scrollTop(getPos);
}
});
});
function RememberScrollPage(scrollPos) {
let UrlsObj = localStorage.getItem('rememberScroll');
let urlsArr = JSON.parse(UrlsObj);
if (urlsArr == null) {
urlsArr = [];
}
if (urlsArr.length == 0) {
urlsArr = [];
}
let urlWindow = window.location.href;
let urlScroll = scrollPos;
let urlObj = {url: urlWindow, scroll: scrollPos};
let matchedUrl = false;
let matchedIndex = 0;
if (urlsArr.length != 0) {
urlsArr.forEach(function (el, index) {
if (el.url === urlWindow) {
matchedUrl = true;
matchedIndex = index;
}
});
if (matchedUrl === true) {
urlsArr[matchedIndex].scroll = urlScroll;
} else {
urlsArr.push(urlObj);
}
} else {
urlsArr.push(urlObj);
}
localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));
}
$(window).scroll(function (event) {
let topScroll = $(window).scrollTop();
console.log('Scrolling', topScroll);
RememberScrollPage(topScroll);
});
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>
I tackle this via using window.pageYOffset . I saved value using event listener or you can directly call window.pageYOffset. In my case I required listener so it is something like this:
window.addEventListener('scroll', function() {
document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
})
And I save latest scroll position in localstorage. So when next time user comes I just check if any scroll value available via localstorage if yes then scroll via window.scrollTo(0,myScrollPos)
sessionStorage.setItem("VScroll", $(document).scrollTop());
var scroll_y = sessionStorage.getItem("VScroll");
setTimeout(function() {
$(document).scrollTop(scroll_y);
}, 300);
I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/
I need to reload a PHP script on my page when I submit a form. When I submit, it has to load on the same page. When the form is submitted, I need to show the confirmation window to the user. However, the problem is that the confirm box is shown while the page is loading (and the page doesn't finish loading until the user selects an option).
------------<? if(){?>
<script>
if(confirm){
}else{
}
</script>
I need the confirm box to be triggered after the page loads completely. Any ideas as to why this might be happening?
Add it to the window.onload event:
window.onload = function () {
if (confirm...) {
...then...
} else {
...else...
}
}
or (what is better) use jquery:
$(function () {
if (confirm...) {
...then...
} else {
...else...
}
});