Session timeout function call - javascript

I have a requirement on session timeout. For that I am using the session time out function. But actually i need to call this function in all my jsp pages and the time should run properly without any reset when navigating through pages. If the session timeout was reached, it should show the pop up. How can I do this?
The function that I used is given below:
var sFlag = "";
function checkIfContinue()
{
sFlag = 1;
if(confirm("Your Session Expired!. Do you wish to continue?"))
{
window.setTimeout('checkIfContinue()', 15*1000); //start the timer again
sFlag = 0;
}
else
{
window.location = '/XMPortal/jsp/X2ALogin.jsp';
}
}
if( sFlag==0 || sFlag == "")
{
window.setTimeout('checkIfContinue()');
}
How can I call the function in the proper manner?

Related

Retry when no response from website

I use the recursive function below, in order to reopen website if httpstatus != 200:
retryOpen = function(){
this.thenOpen("http://www.mywebsite.com", function(response){
utils.dump(response.status);
var httpstatus = response.status;
if(httpstatus != 200){
this.echo("FAILED GET WEBSITE, RETRY");
this.then(retryOpen);
} else{
var thisnow = hello[variable];
this.evaluate(function(valueOptionSelect){
$('select#the_id').val(valueOptionSelect);
$('select#the_id').trigger('change');
},thisnow);
}
});
}
The problem is that sometimes the retryOpen function does not even go as far as to callback function(response){}. Then, my script freezes.
I wonder how one could change the function to be able to recursively try to open website again if there is no response from website (not even some error code as 404 or something)? In other words, how to rewrite the retryOpen function so it reruns when the function does not reach callback after a certain amount of time?
I would try something like this. Please note this is untested code, but should get you on the correct path
retryOpen = function(maxretry){
var count = 0;
function makeCall(url)
{
this.thenOpen(url, function(response){
utils.dump(response.status);
});
}
function openIt(){
makeCall.call(this,"http://www.mywebsite.com");
this.waitFor(function check() {
var res = this.status(false);
return res.currentHTTPStatus === 200;
}, function then() {
var thisnow = hello[variable];
this.evaluate(function(valueOptionSelect){
$('select#the_id').val(valueOptionSelect);
$('select#the_id').trigger('change');
},thisnow);
}, function timeout() { // step to execute if check has failed
if(count < maxretry)
{
openIt.call(this);
}
count++
},
1000 //wait 1 sec
);
}
openIt();
}

AngularJS page causes Chrome to use up huge tab memory in background

I have a, fairly simple, AngularJS page that simply uses a service to pull data from the backend and show it on screen using an ng-repeat.
During normal usage after 10mins the memory for the page stabilises at around 100mb. If I switch tabs so that this page is no longer focused - it is in the background it will balloon in memory up until 1gb and then itll crash.
I am using $interval to refresh the data and I read recently that Chrome throttles intervals and timeouts when a page is in the background. Shouldn't this prevent this from happening? Anything I can do? As a last resort I have considered switching to requestAnimationFrame as I know this won't get called when the page is in the background.
$interval($scope.update, $scope.refreshInterval);
//
//
//
$scope.update = function () {
$scope.inError = false;
scheduleAppAPIservice.getSchedules().then(
function (response) {
$scope.schedules = null;
$scope.schedules = response.data;
angular.forEach($scope.schedules, $scope.createNextExecutionLabel);
angular.forEach($scope.schedules, $scope.createTrclass);
angular.forEach($scope.tabs, $scope.assignSchedulesToTab);
$scope.loading = false;
},
function () {
$scope.inError = true;
//console.log("failed getSchedules");
});
};
//
//
//
$scope.createNextExecutionLabel = function (schedule) {
schedule.nextExecutionDate = moment(schedule.NextExecution);
schedule.endExecutionDate = moment(schedule.EndExecution);
if (schedule.nextExecutionDate.year() > $scope.finishedCutoffYear) {
schedule.nextExecutionLabel = "Never";
}
else if (schedule.IsCurrentlyExecuting) {
schedule.nextExecutionLabel = "Running";
if (!isNaN(schedule.CurrentProgress) && schedule.CurrentProgress != 0) {
schedule.nextExecutionLabel += " (" + schedule.CurrentProgress + "%)";
}
else {
schedule.nextExecutionLabel += "...";
}
}
else if (schedule.nextExecutionDate < moment()) {
schedule.nextExecutionLabel = "Overdue";
}
else {
schedule.nextExecutionLabel = $filter('emRelativeTime')(schedule.nextExecutionDate);
}
}
//
//
//
$scope.createTrclass = function (schedule) {
var trclass = "system";
if (schedule.IsDisabled) {
trclass = "disabled";
}
else if (schedule.IsUserSchedule) {
if (schedule.nextExecutionDate.year() > $scope.finishedCutoffYear && schedule.ExecuteOnEvent == 0)
trclass = "finished";
else
trclass = "active";
}
schedule.trclass = trclass;
};
//
//
//
$scope.assignSchedulesToTab = function (tab) {
tab.scheduleCount = $scope.schedules.filter(function (x) {
return x.trclass == tab.label.toLowerCase();
}).length;
};
I don't have any information about background tab throttling so, the theory in this answer may not be true.
$interval works, say, every 5 seconds.
But the successful promise inside the $interval may not be resolved in 5 seconds.
So if scheduleAppAPIservice.getSchedules() doesn't resolve in 5 seconds for some reason, an increased numbers of promises will consume memory on each $interval cycle.
You may cancel previous request when starting a new one on $interval, or you can use $timeout + manual invocation of the next request when promise completed to make sure there is nothing that consumes memory in an uncontrolled way.

How to know if browser tab is already open using Javascript?

How to know or check if the two browser tab is already open and if those tab are open, the user will receive an alert box or msg box saying that 'the url is already open', something like that, in pure/native JavaScript? This browser tab is contain an external website which is I don't have any privileges to manipulate or change it. Thanks
Example URLs
yahoo.com and google.com
I want to alert the user if there's already open tab for yahoo.com and google.com
And I want to use tabCreate to open the url like this:
tabCreate("http://maps.google.com/", "tabMapsPermanentAddress");
mean to open a new tab, it is use in creating chrome extension
You may use something like following
<!-- HTML -->
<a id="opener">Open window</a>
// JavaScript
var a = document.getElementById('opener'), w;
a.onclick = function() {
if (!w || w.closed) {
w = window.open("https://www.google.com","_blank","menubar = 0, scrollbars = 0");
} else {
console.log('window is already opened');
}
w.focus();
};
Working jsBin | More on window.open method
If you want to control more than one window, use the snippet below
<!-- HTML -->
Open google.com |
Open yahoo.com
//JavaScript
window.onload = function(){
var a = document.querySelectorAll('.opener'), w = [], url, random, i;
for(i = 0; i < a.length; i++){
(function(i){
a[i].onclick = function(e) {
if (!w[i] || w[i].closed) {
url = this.href;
random = Math.floor((Math.random() * 100) + 1);
w[i] = window.open(url, "_blank", random, "menubar = 0, scrollbars = 0");
} else {
console.log('window ' + url + ' is already opened');
}
e.preventDefault();
w[i].focus();
};
})(i);
}
};
Working jsBin
If you don't want them to load in separated window, just exclude this line
random = Math.floor((Math.random()*100)+1);
and remove random reference from the next line
w[i] = window.open(url, "_blank", random, "menubar=0,scrollbars=0");
Side note: As you can see above, we created two windows with some third party content; you should know that there's no way to get any reference (to the parent/opener window) from them.
One basic idea is to store the tab count in either a cookie or localStorage, incrementing it on page load and decrementing it on page unload:
if (+localStorage.tabCount > 0)
alert('Already open!');
else
localStorage.tabCount = 0;
localStorage.tabCount = +localStorage.tabCount + 1;
window.onunload = function () {
localStorage.tabCount = +localStorage.tabCount - 1;
};
Try opening this fiddle in multiple tabs.
Note that this technique is pretty fragile, though. For example, if for some reason the browser crashes, the unload handler won't run, and it'll go out of sync.
The answer by Casey Chu works fine until the browser crashes with the page open. On any next execution, the localStorage object will have initialized tabCount with non zero value. Therefore a better solution is to store the value in a session cookie. The session cookie will be removed when browser exits successfully. When the browser crashes the session cookie will actually be preserved but fortunately only for one next execution of the browser.
Object sessionStorage is distinct for each tab so it cannot be used for sharing tab count.
This is the improved solution using js-cookie library.
if (+Cookies.get('tabs') > 0)
alert('Already open!');
else
Cookies.set('tabs', 0);
Cookies.set('tabs', +Cookies.get('tabs') + 1);
window.onunload = function () {
Cookies.set('tabs', +Cookies.get('tabs') - 1);
};
This answer: https://stackoverflow.com/a/28230846 is an alternative that doesn't require Cookies/js-cookie library. It better suited my needs. In a nutshell (see linked answer for full description):
$(window).on('storage', message_receive);
...
// use local storage for messaging. Set message in local storage and clear it right away
// This is a safe way how to communicate with other tabs while not leaving any traces
//
function message_broadcast(message)
{
localStorage.setItem('message',JSON.stringify(message));
localStorage.removeItem('message');
}
// receive message
//
function message_receive(ev)
{
if (ev.originalEvent.key!='message') return; // ignore other keys
var message=JSON.parse(ev.originalEvent.newValue);
if (!message) return; // ignore empty msg or msg reset
// here you act on messages.
// you can send objects like { 'command': 'doit', 'data': 'abcd' }
if (message.command == 'doit') alert(message.data);
// etc.
}
Just going to throw this up here, because I wish I had something like it. Make what you will of it.
If you want a solution for checking if you are the active tab that doesn't require a cookie, works as a React hook, and works whether or not the browser crashes, you can use this useIsActiveTab webhook which returns true if you are the most recent active tab/window. You can also set yourself as the active tab with activateTab.
import { useEffect, useState } from 'react';
const CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const CHARACTERS_LENGTH = CHARACTERS.length;
function generateTabId() {
let result = '';
const prefix = 'TAB_';
const length = 15;
for (let i = 0; i < length - prefix.length; i++) {
result += CHARACTERS.charAt(Math.floor(Math.random() * CHARACTERS_LENGTH));
}
if (prefix.includes('_')) {
return `${prefix}${result}`;
}
return `${prefix}_${result}`;
};
const tabId = generateTabId();
export function activateTab(): void {
localStorage.setItem('activeTab', tabId);
const event = new Event('thisStorage');
window.dispatchEvent(event);
}
export function useIsActiveTab(): boolean {
const [isActiveTab, setIsActiveTab] = useState(false);
useEffect(() => {
setActiveTab();
function updateIsActiveTab() {
setIsActiveTab(checkIfActiveTab());
}
window.addEventListener('storage', updateIsActiveTab);
window.addEventListener('thisStorage', updateIsActiveTab);
updateIsActiveTab();
return () => {
window.removeEventListener('storage', updateIsActiveTab);
window.removeEventListener('thisStorage', updateIsActiveTab);
};
}, []);
return isActiveTab;
}
function checkIfActiveTab(): boolean {
const activeTab = localStorage.getItem('activeTab');
if (!activeTab) {
console.error('localStorage.activeTab is not set');
return true;
}
if (activeTab === tabId) {
return true;
}
return false;
}
function setActiveTab(): void {
localStorage.setItem('activeTab', tabId);
}

Javascript setInterval not working?

I am working on a bit of code in Javascript that polls a time consuming process that is running in a webservice and returns the status every two seconds. The processPoll function is never getting hit and I can not figure out why the setInterval does not work. I think I have the scope right so I'm not sure why processPoll does not start.
var processId;
var timerId;
function processStartReturn(retVal) {
if ((retVal != null) && (retVal != "")) {
processId = retVal;
timerId = setInterval(processPoll, 2000);
alert(processId); --> alerts correct Id
}
}
function processPoll() {
alert("This alert never shows up!");
WebService.MyFunction(processId, 0);
}
function startPoll() {
var appName = document.getElementById("appName").value;
var threadId = appName + "object";
processStartReturn(threadId);
}
Edit: I have added the startPoll() function that is started with an onclientclick event.

Strange setTimeout clearing behaviour with jQuery AJAX

So, I'm trying to set a timeout on each request that is sent and work out if one is taking "too long". I'm watching the network tab and each request is well under 300ms, however 'too long' gets logged 6 times! (the number of requests I'm sending). Is there something I'm doing wrong with variables, setTimeouts or something?
var ajaxMonitor = {};
function timingStart() {
var url = arguments[2].url;
ajaxMonitor[url] = {};
ajaxMonitor[url].timer = setTimeout(function () {
console.log('too long');
}, 300);
}
function timingEnd() {
var url = arguments[2].url;
clearTimeout(ajaxMonitor[url].timer);
}
$(document).ajaxSend(timingStart);
$(document).ajaxComplete(timingEnd);
As pointed out in the comment it might be because you are calling the same url multiple times. If that is the case, one way to fix that problem is to clear the interval before setting it:
function timingStart() {
var url = arguments[2].url;
clear(url);
ajaxMonitor[url] = {};
ajaxMonitor[url].timer = setTimeout(function () {
console.log('too long');
}, 300);
}
function timingEnd() {
var url = arguments[2].url;
clear(url);
}
function clear(url) {
if(ajaxMonitor[url])
clearTimeout(ajaxMonitor[url].timer);
}
$(document).ajaxSend(timingStart);
$(document).ajaxComplete(timingEnd);

Categories