I'm trying to create a navigation system for an internal website.
To do so I'm creating an array by means of javascript that tracks the url of the page and with each new page I'm pushing that new url into the array.
Problem is, each new page seems to be overwriting the last page.
This is what is in my javascript file ... notice I only create a new array if the array doesn't already exist (it will be deleted when the person leaves the website).
var myURL = document.URL;
if (typeof myHistory == "undefined" || !(myHistory instanceof Array)) {
var myHistory = [];
}
myHistory.push(myURL);
var last_element = myHistory[myHistory.length - 1];
var number_rows = myHistory.length;
This what I'm using to see the values in the html ...
<script type="text/javascript">
<!--
document.write(last_element);
document.write(number_rows);
// -->
</script>
It's displaying the URL (last_element) as desired but number_rows remains at 1 when I browse between pages rather than go up to 2, 3, 4, etc which is what I hope to achieve.
Can anyone give me any pointers?
Every time you refresh a page, JavaScript is refreshed anew. If you need to have data persistence, you'll need to use cookies, localStorage, or server-side data storage.
All of those options will require that you serialize to and deserialize from strings.
Here's a quick example of how you could do this using localStorage:
//closure to prevent global pollution
//it's good to be green
(function () {
"use strict";
var history,
url;
//set url here
//I'm making the assumption that no url will have a ',' char in it
history = localStorage['history'].split(',');
history.push(url);
localStorage['history'] = history.join(',');
console.log(url, history.length);
}());
When you browse between pages the javascript environment is re-created on each page. So you are always starting with an empty array.
Related
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!
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
I have a URL to a text file which specifies what my menu controller is called and whether I am in debug mode etc....
eg. menudriver=MenuController.aspx&debug=true&webroot=https://somewebsite.com
Now what I would like to do is have this loaded into a variable in javascript then also each URL variable also saved into some array.
Once this has been done I have a menu that is dynamically populated according to what is received from a separate URL. Here is an as3 example:
var request:URLRequest = new URLRequest(WebRoot+fill+CallerURI+"?KR_ID="+Math.random());
This URL basically contains labels as well as URI for buttons in my menu.
How is this done is javascript?
I do have a completed implementation in as3 but I am battling to find the javascript alternatives.
in Reply to the comment, pure javascript solution
var query = (function() {
function decode(string) {
return decodeURIComponent(string.replace(/\+/g, " "));
}
var result = {};
if (location.search) {
location.search.substring(1).split('&').forEach(function(pair) {
pair = pair.split('=');
result[decode(pair[0])] = decode(pair[1]);
});
}
return result;
})();
it use ECMAScript 5 function forEach, if you need to support browsers that don't support it, you can use es5-shim.
I'm making a websites that displays noise measurement data from different locations. The data for each location is captured on a sound level meter device and it is then read with a windows-based application. The application then uploads data on a web server as a .js file with an array variable in it. This .js files are refreshed every 5 minutes.
I first created a javascript application that displays live data for a single measuring unit. But now I need to display data on a map for all the locations. The problem is that the windows application on each location makes a file with the same name and same variables only on another location. I'm having some trouble with reading the correct data.
This is what I did so far:
function removejscssfile(filename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}
function updateData(){
var numberOfNoiseSniffers = noiseSniffers.length-1;
var j = 0;
for (i=0;i<=numberOfNoiseSniffers;i++) {
file = '../'+ noiseSniffers[i] + "/" + "CurrentMeasurement.js";
$.include(file,function(){
laeq[j] = currentMeas[1][1];
lastUpdate[j] = currentMeas[0][1];
if (j==numberOfNoiseSniffers){
updateMarkers();
}
removejscssfile(file[0], "js");
j++;
});
}
t=setTimeout(function() { updateData() }, 300000);
}
$(function (){
map = new google.maps.Map(document.getElementById("gMap"), myOptions);
//noiseSniffers is an array where I have save all the folder names of different measurement locations
var numberOfNoiseSniffers = noiseSniffers.length-1;
var j = 0;
for (i=0;i<=numberOfNoiseSniffers;i++) {
var file = '../'+ noiseSniffers[i] + "/" + "CurrentMeasurement.js";
//I am using include plugin for jquery to include files because it has a callback for when a file is actually loaded
$.include(file,function(){
//a set of global arrays that keep the data from the loaded file and this data is then displayed in google maps markers
laeq[j] = currentMeas[1][1];
lastUpdate[j] = currentMeas[0][2];
latitude[j] = systemstats[12][5];
longitude[j] = systemstats[11][6];
//checking to see if I am in the process of including the last file
if (j==numberOfNoiseSniffers){
//a function that creates google maps markers
createMarkers();
}
//after that I remove the files that were just included and read
removejscssfile(file, "js");
j++;
});
}
setTimeout(function() { updateData() }, 300000);
});
I got the function for removing my .js file here: Dynamically removing an external JavaScript or CSS file.
And this is the jquery plugin for loading the .js file: Include File On Demand.
The initial load usually works (sometimes it happens that only one or no markers get loaded. But the update function mostly returns the same data for both locations.
So what I want to know is, how can I firstly make my code working and how to optimize it. I posted just the main parts of the javascript code, but I can provide all the code if it is needed. Thanks for any help.
I think you need some sort of JSONP-like solution.
Basically load data on the server side, then wrap it in a method call before returning it to client side. Your response should look something like this:
var location_data = [1,2,3,4]
updateLocation('location_id', location_data)
Now you define an updateLocation() function in your client side script. Now, every time you need new data, you create new 'script' tag with src pointing to your server side. When the response is loaded, your updateLocation() will be invoked with correct params.
I hope this is clear enough
You can maybe try some form of namespacing
i exactly dont understood your problem, but you may try this
//put your code inside an anonymous function and execute it immediately
(function(){
//your javascript codes
//create variable with same names here
//
})();
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.