Store Cookie On Window UnLoad (Window.Variable) - javascript

UPDATE:
I stopped using an array (As I originally was when I first posted this)
I seem to be having issues with my script. I don't know why, but when the web page unloads, the window.SpecificURL doesn't save. I know the script to get it is fine, the script to store it is as well. Is there something I am missing? Here is my code:
var UWDV = window.UWDV = "UserWindowDataV2"; // What Version Is The User Window Data Stored As
setTimeout(function(){ // Wait So Stuff Can Load
if (!window.SpecificURL){ // If Not A Special URL To Load
window.SpecificURL = GetCookie(UWDV); // Get The User's Last Known State
var WSURL = window.SpecificURL; // Set Variable
// if (typeof WSURL[0]!=="string" || WSURL[0].length < 2){SetCookie(UWDV, ["home"]); WSURL = ["home"];} // If It Glitched, Fix Automatically
console.log(WSURL);
fillpage(WSURL); // Load Page PC
mobileload(WSURL); // Load Page Mobile
window.SpecificURLReady = true;
}
}, 100);
window.addEventListener("unload", function(){SetCookie(window.UWDV, window.SpecificURL);}); // Add Save Page Status Function
(FYI: The fillpage & mobileload functions set window.SpecificURL to whatever the choice was.)
(FYI2: This is fired 2 seconds after the website loads)

I fixed it by switching from Arrays to save data, to a string. Sorry for any inconvenience to someone trying to solve this!

Related

opening a new tab loses the arraylist in local storage javascript stack overflow

My application work tries to store some data on my local storage which works fine when i am not opening any new tab or window, but when i open a new tab, my array loses all its previous stored data and stores only the current data. Please suggest what i am doing wrong here.
my code is something like this:
getCurrReqIdList = [];
localStorage.setItem('getCurrReqIdList', JSON.stringify(getCurrReqIdList));
var retrievedData = localStorage.getItem('getCurrReqIdList');
var getFinalReqIdList = JSON.parse(retrievedData);
if(getFinalReqIdList.length > maxCurrentConnectionLength) {
console.log('Hello');
getFinalReqIdList.shift();
getCurrReqIdList.shift();
localStorage.setItem('getCurrReqIdList',JSON.stringify(getFinalReqIdList));
}
The post is a bit confusing, but I bet you have the lines
getCurrReqIdList = [];
localStorage.setItem('getCurrReqIdList', JSON.stringify(getCurrReqIdList));
running every time you load your page, for initializing the store. So when you open a new tab, it loads the page and override the local storage value with an empty array.
You page should run something like:
getCurrReqIdList = localStorage.getItem('getCurrReqIdList');
if(getCurrReqIdList) {
getCurrReqIdList = JSON.parse(getCurrReqIdList);
} else {
getCurrReqIdList = [];
localStorage.setItem('getCurrReqIdList', JSON.stringify(getCurrReqIdList));
}
It should not happen so because data stored in localStorage object will be shared between tabs also.
You might have some other code which will reset or delete the data from localStorage as soon as you open a new tab.
According to: This
you can't share data between multiple tabs using sessionStorage, because a new page is a new session.
You need to replace
setStorageType('sessionStorage')
by
setStorageType('localStorage') // which is default

save to localstorage dynamic JQuery rows

I think I have a major fault in my webpage design. I need to save the content if I reboot the computer or close the webpage.
I do not have access to any type of a database server only MS Access. I was thinking of utilizing localstorage as the page will be constantly viewed from the same computer.
I found this example [link]Edit functionality using javascript and local storage however I am not sure if it will work.
Can someone look at my example and let me know if I can do this or if I need to abandon this and start over.
$(document).ready(function () {
var id = 0;
// Add button functionality
$("table.dynatable button.add").click(function () {
id++;
var master = $(this).parents("table.dynatable");
// Get a new row based on the prototype row
var prot = master.find(".prototype").clone(true);
prot.attr("class", "")
prot.find(".id").attr("value", id);
master.find("tbody").append(prot);
});
// Remove button functionality
$(document).on("click", "table.dynatable button.remove", function () {
$(this).parents("tr").remove();
});
});
http://jsfiddle.net/deaconf19/csL68/
Thanks
If you are running the web page from a web-server -- that is, your URL begins with http:// or https://, then yes, you can use localStorage to save data.
If you are running the file directly from your hard drive, that is, your url begins with file:, then you'll have trouble. Chrome won't let you use localStorage -- I don't remember if Firefox does.
(If you need to run this from your local hard drive and not a server, and you are running under Windows, you can turn the file into an HTA and save data to a regular file.)

KDE plasmoid ind autorefresh

I'm trying to write KDE4 plasmoid in JavaScript, but have not success.
So, I need to get some data via HTTP and display it in Label. That's working well, but I need regular refresh (once in 10 seconds), it's not working.
My code:
inLabel = new Label();
var timer= new QTimer();
var job=0;
var fileContent="";
function onData(job, data){
if(data.length > 0){
var content = new String(data.valueOf());
fileContent += content;
}
}
function onFinished(job) {
inLabel.text=fileContent;
}
plasmoid.sizeChanged=function()
{
plasmoid.update();
}
timer.timeout.connect(getData);
timer.singleShot=false;
getData();
timer.start(10000);
function getData()
{
fileContent="";
job = plasmoid.getUrl("http://192.168.0.10/script.cgi");
job.data.connect(onData);
job.finished.connect(onFinished);
plasmoid.update();
}
It gets script once and does not refresh it after 10 seconds. Where is my mistake?
It is working just fine in here at least (running a recent build from git master), getData() is being called as expected. Can you see any errors in the console?
EDIT: The problem was that getUrl() explicitly sets NoReload for KIO::get() which causes it load data from cache instead of forcing a reload from the server. Solution was to add a query parameter to the URL in order to make it force reload it.

getting last page URL from history object - cross browser?

Is it possible to get last page URL from the history object? I've come accross history.previous but that's either undefined or protected from what I've seen.
Not from the history object, but from document.referrer. If you want to get the last actual page visited, there is no cross-browser way without making a separate case based on support for each property.
You cant get to history in any browser. That would be a serious security violation since that would mean that anyone can snoop around the history of their users.
You might be able to write a Browser Helper Object for IE and other browsers that give you access to that. (Similar to the google toolbar et al). But that will require the users to allow that application to run on their machine.
There are some nasty ways you can get to some history using some "not-so-nice" ways but I would not recommend them. Look up this link.
Of course, as people have said, its not possible. However what I've done in order to get around this limitation is just to store every page loaded into localStorage so you can create your own history ...
function writeMyBrowserHistory(historyLength=3) {
// Store last historyLength page paths for use in other pages
var pagesArr = localStorage.myPageHistory
if (pagesArr===null) {
pagesArr = [];
} else {
pagesArr = JSON.parse(localStorage.myPageHistory);
pagesArr.push(window.location.pathname) // can use whichever part, but full url needs encoding
}
if (pagesArr.length>historyLength) {
// truncate the array
pagesArr = pagesArr.slice(pagesArr.length-historyLength,pagesArr.length)
}
// store it back
localStorage.myPageHistory = JSON.stringify(pagesArr);
// optional debug
console.log(`my page history = ${pagesArr}`)
}
function getLastMyBrowserHistoryUrl() {
var pagesArr = localStorage.myPageHistory
var url = ""
if (pagesArr!==null) {
pagesArr = JSON.parse(localStorage.myPageHistory);
// pop off the most recent url
url = pagesArr.pop()
}
return url
}
So then on a js in every page call
writeMyBrowserHistory()
When you wanna figure out the last page call
var lastPageUrl = getLastMyBrowserHistoryUrl()
Note: localStorage stores strings only hence the JSON.
Let me know if I have any bugs in the code as its been beautified from the original.

Using javascript for pinging a webapp to keep session open

I'm writing a greasemonkey script to keep session open on a webapp I use for work.
Which javascript command would you use to create some feedback with the server and ensure the session doesn't fall without having to bother the user making a complete refresh of the page?
I've solved the issue using:
function keepAlive() {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "/restricted_file_url");
httpRequest.send(null);
}
setInterval(keepAlive, 840000); //My session expires at 15 minutes
Using some tips from Jesse's answer, here's the complete code.
You will need to update the #match param with your site's domain
// ==UserScript==
// #name Auto session extender
// #namespace http://obive.net/
// #version 0.2
// #description Automatically extend server-side session
// #author Charlie Hayes
// #match http://obive.net/
// #grant GM_getValue
// #grant GM_setValue
// #noframes
// ==/UserScript==
(function() {
'use strict';
console.log('The session for this site will be extended automatically via userscript.');
var minute = 60*1000;
var refreshTime = 15 * minute;
var iframe = document.createElement("iframe");
iframe.style.width = 0;
iframe.style.height=0;
var loc = window.location;
var src = loc.protocol +'//' + loc.host + loc.pathname;
src += loc.search ? (loc.search + '&') : '?';
src += 'sessionextendercachebuster=';
var reloadIframe = function(){
var time = new Date().getTime();
var lastRefresh = GM_getValue('lastRefresh');
var timeSinceLastRefresh = time - lastRefresh;
if (!lastRefresh || timeSinceLastRefresh > refreshTime - minute) {
console.log('Auto-extending session');
iframe.src = src + time;
GM_setValue('lastRefresh',time);
setTimeout(reloadIframe, refreshTime);
setTimeout(function(){
// Unload the iframe contents since it might be taking a lot of memory
iframe.src='about:blank';
},10000);
}else{
console.log('Another tab/window probably refreshed the session, waiting a bit longer');
setTimeout(reloadIframe, refreshTime - timeSinceLastRefresh - minute);
}
};
setTimeout(reloadIframe, refreshTime);
document.body.appendChild(iframe);
})();
Second choice
If you absolutely insist on using Greasemonkey, any element.click() method on any event that submits an XMLHTTPrequest should do.
First choice
If you are willing to use a solution that does not require you to write a Greasemonkey script:
ReloadEvery 3.0.0, by Jaap Haitsma
This reloads web pages every so many seconds or minutes. The function is accessible via the context menu (the menu you get when you right click on a web page) or via a drop down menu on the reload button.
It's not what you asked for, but unless you simply want to brush up on your javascript skills, this is probably the most straight-forward method for solving your problem.
If you want to write JavaScript to solve this (the other answers are a lot easier and I would recommend going the easier route), here's what I would do:
Call document.createElement("iframe") to create an iframe
Size the iframe to 0x0, style.display = "none", set the ID to something, and set the src property to a page on the site that will extend your session
Use document.body.appendChild to add the iframe to the page
Using setTimeout refresh the iFrame using window.frames['iframeID'].location.reload(true); and also call setTimeout to refresh the page again.
See if the other answers would work because using JavaScript seems like it would be more trouble than it's worth.
I can definitely recommend the solution suggested by dreftymac!
If you don't want to worry about remembering to click the reloadevery option, your grease monkey script is simply
window.location.href = window.location.href
This is presuming you don't want to keep the page constantly refreshing, as suggested by others.
Ordinarily, if you were simply looking to ping the server, you would probably do best to do something like use an image that you know exists on the remote server, and check it's height - thus creating traffic.
However, your problem (I presume) needs to access some limited area of the website, in order to keep the session active... with this being the case (and the fact that you can't directly ping), find a page that is 'restricted' and do an Ajax call, or similar. Don't quote me on this, as I'm by no means a JavaScript expert... just throwing out a potential solution.

Categories