Display logs from the database in a textbox via html and javascript - javascript

I have a table in the Database which stores the history of queries to my website.
I want to display them on the page, and update in real-time via javascript.
I've already implemented It, but the website becames very laggy.
Here is how It looks:
I have an Api on my website to get All the logs after a specific time.
I call It in javascript every 5 seconds passing the time of page loading, and updating the content of the textbox. So we see all the logs since we entered the page, and they are updating every 5 seconds.
The problem is, that the website becames very laggy in ~5 minutes, and the textbox stops updating. Also I get an alert from my browser saying something like "This page is slowing down your browser".
my logs.js:
let server_ip = location.host
var start_of_the_page = sessionStorage.getItem('start_of_the_page');
if (!start_of_the_page) { // if no such value exists
start_of_the_page = getCurrentHawkeyeTime();
// start_of_the_page = utcToTimestamp(new Date(Date.UTC(2022, 3, 1, 0, 0, 0, 0)));
}
// save data to sessionStorage
sessionStorage.setItem('start_of_the_page', start_of_the_page);
// adding jetson logs to readonly textarea
let floatingTextArea = document.getElementById("floatingTextArea");
let xhr4logs = new XMLHttpRequest();
let url_str = 'http://' + server_ip + '/get_web_logs?time=' + start_of_the_page;
xhr4logs.open("POST", url_str, true);
console.log("created xhr with such url: " + url_str);
xhr4logs.send();
// adding event that is triggered when the response is fully received
xhr4logs.onload = function() {
console.log(xhr4logs.status + " " + xhr4logs.response);
let obj = JSON.parse(xhr4logs.response);
// let groups = obj.info.split("\n").filter((a) => a); // getting non-empty lines
floatingTextArea.value = obj.info;
floatingTextArea.scrollTop = floatingTextArea.scrollHeight;
}
setInterval(function() {
return function() {
console.log("doing new cycle...");
let url_str = 'http://' + server_ip + '/get_web_logs?time=' + start_of_the_page;
xhr4logs.open("POST", url_str, true);
console.log("created xhr with such url: " + url_str);
xhr4logs.send();
};
}(), 5000);
Would be happy to hear any comments on what could slow down the browser and if there is any other approach to display the data from the database updating it regularly.

Related

JavaScript - How to send multiple XMLHttp requests or force the XMLHTTP request to wait till I get the desired response?

I am making a GET request to the api using XMLHttpRequests. The api takes in a "uuid" value denoted by the variable "a" here as a parameter, uses that value for processing and is supposed to spit out some information that I am trying to print to the console.
However, the problem I am running into is that, whenever the api successfully receives the uuid value it returns a message where the newresponse.response.status is Initiated. However I want to wait till the newresponse.response.status is Success (this usually takes a short bit like 3-4 seconds more).
The original code is shown below:
function getrequestresults(status, response) {
let parse = JSON.parse(response);
let a = parse.uuid;
let newrequest = new XMLHttpRequest();
newrequest.open('GET', "http://localhost:5000/api/v1/dags/results" + "?" + "uuid" + "=" + a, true);
newrequest.onload = function() {
//console.log(newrequest.status);
console.log(newrequest.response);
};
newrequest.send();
}
One of the attempts I made at fixing this was as follows:
function getrequestresults(status, response) {
let parse = JSON.parse(response);
let a = parse.uuid;
let newrequest = new XMLHttpRequest();
newrequest.open('GET', "http://localhost:5000/api/v1/dags/results" + "?" + "uuid" + "=" + a, true);
newrequest.onload = function() {
while (newrequest.response.status != "Success") {
//the following line was just to see what's going on, idea was to keep looping till, desired status is reached
console.log(newrequest.response);
}
//console.log(newrequest.status);
console.log(newrequest.response);
};
newrequest.send();
}
However, this did not work as it seems that the "onload" function only runs once, whereas I need it to run multiple times until newrequest.response.status is Success.
I am quite new with sending XMLHttpRequests and some help would be appreciated. Thanks.

createFile() in google Apps Script is not functioning properly

I am trying to create a file. It works fine when I run the following code segment from the debugger in apps script. However, when I run it real time from the spreadsheet, it says I do not have permission to call createfile. Everything that is logged is identical. The issue is not I do not have authority as I am the only one in the spreadsheet and am the owner. The purpose of the CSV is to move it from my google drive into data for BigQuery
function saveAsCSV(row) { //Doc to Csv
//row = 3; //when this is uncommented and ran from the debugger, it works.
try{
var fileName= Date.now()
fileName = fileName + ".csv";
var csvFile = convertRangeToCsvFile_(fileName,row);
Logger.log(csvFile); //Both times ran on the spreadsheet and from debug equals the same.
DriveApp.createFile(fileName, csvFile);
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("New and Open").getRange("J" + row.toString()).setValue("");
loadCsv(fileName);
}
catch(e){Logger.log("B" + e.message);} //No permission to create file
}
function convertRangeToCsvFile_(csvFileName, r) {
var ws = SpreadsheetApp.getActiveSpreadsheet();
try {
//var data = ws.getValues();
var csvFile = undefined;
var csv = "";
var row = r;
var datArray = Create2DArray(1,19);
datArray[0][0] = ws.getRange("A" + row.toString()).getValue().toString().toUpperCase();
datArray[0][1] = ws.getRange("B"+row.toString()).getValue().toString().toUpperCase();
datArray[0][2] = ws.getRange("C"+row.toString()).getValue().toString().toUpperCase();
datArray[0][3] = ws.getRange("D"+row.toString()).getValue().toString().toUpperCase();
datArray[0][4] = ws.getRange("E"+row.toString()).getValue().toString().toUpperCase();
datArray[0][5] = ws.getRange("F"+row.toString()).getValue().toString().toUpperCase();
datArray[0][6] = ws.getRange("G"+row.toString()).getValue().toString().toUpperCase();
datArray[0][7] = ws.getRange("H"+row.toString()).getValue().toString().toUpperCase();
datArray[0][8] = ws.getRange("I"+row.toString()).getValue().toString().toUpperCase();
datArray[0][9] = new Date(ws.getRange("K"+row.toString()).getValue().toString()).getHours();
datArray[0][10] = new Date(ws.getRange("K"+row.toString()).getValue().toString()).getMinutes();
datArray[0][11] = new Date(ws.getRange("L"+row.toString()).getValue().toString()).getHours();
datArray[0][12] = new Date(ws.getRange("L"+row.toString()).getValue().toString()).getMinutes();
datArray[0][13] = new Date(ws.getRange("M"+row.toString()).getValue().toString()).getHours();
datArray[0][14] = new Date(ws.getRange("M"+row.toString()).getValue().toString()).getMinutes();
datArray[0][15] = new Date(ws.getRange("N"+row.toString()).getValue().toString()).getTime();
datArray[0][16] = new Date(ws.getRange("N"+row.toString()).getValue().toString()).getFullYear();
datArray[0][17] = new Date(ws.getRange("N"+row.toString()).getValue().toString()).getMonth();
datArray[0][18] = new Date(ws.getRange("N"+row.toString()).getValue().toString()).getDate();
for(var i = 0; i < 19; i++){
if(datArray[0][i] == ""){if(i > 9){datArray[0][i] = 0;} else{datArray[0][i] = "nil";} }
if(i < 18){csv += '"' + datArray[0][i] + '"' + ",";}
else{ csv += '"' + datArray[0][i] + '"'; }
}
Logger.log("A " + csv);
Logger.log(csv + "\n" + datArray[0].join(","));
csvFile = csv;
return csvFile;
}
catch(err) {
Logger.log("C" + err);
Browser.msgBox(err);
}
}
You mention in your comment on my answer that you are using onEdit to trigger the script. Since this is a Simple Trigger, your current approach will not work. When you use simple triggers to run an Apps Script, it runs in a sandbox with reduced permissions.
See: https://developers.google.com/apps-script/guides/triggers/#restrictions
The best I can recommend is create a custom menu option with a UI popup asking for the row number to export. If the code is triggered from a menu by the user, it runs with full permission to access that users account.
Depending on your use-case, a scheduled trigger might work too. It could run every 10 minutes or every Hour and export any changes to the spreadsheet. In this case the Apps Script runs as you, with permission to access your account, and the resulting CSV would be created on your drive.
Details on how to create a custom menu: https://developers.google.com/apps-script/guides/triggers/#onopen
Details on how to create a form for the user: https://developers.google.com/apps-script/guides/ui-service
Details on time driven triggers: https://developers.google.com/apps-script/guides/triggers/installable#time-driven_triggers

InDesign ExtendScript script sometimes creates a corrupted PDF during export

I've had this problem for a while, now. Close to the end of my "Proofing" script, the currently opened document in InDesign is to be exported to two different .pdf files. The first is password-protected while the second is not. I don't seem to have any problems with the latter, but the former often becomes corrupted somehow and cannot be opened by any PDF reader, including Acrobat itself. Here's the code block that does the exporting (it is not runnable by itself, btw):
/********** BEGIN PDF EXPORTING **********/
// First, let's create and set PDF export preferences.
// This begins with creating a temporary preset if it doesn't already exist.
// This preset will be used for both the Proof page and the Cover sheet.
var tempPreset = app.pdfExportPresets.item("tempPreset");
try
{
tempPreset.name;
}
catch (eNoSuchPreset)
{
tempPreset = app.pdfExportPresets.add({name:"tempPreset"});
}
with (tempPreset)
{
acrobatCompatibility = AcrobatCompatibility.ACROBAT_5;
bleedMarks = false;
colorBars = false;
colorBitmapCompression = BitmapCompression.AUTO_COMPRESSION;
colorBitmapQuality = CompressionQuality.MAXIMUM;
colorBitmapSampling = Sampling.BICUBIC_DOWNSAMPLE;
colorBitmapSamplingDPI = 300;
compressTextAndLineArt = true;
cropImagesToFrames = true;
cropMarks = false;
exportGuidesAndGrids = false;
exportNonprintingObjects = false;
exportReaderSpreads = false;
exportWhichLayers = ExportLayerOptions.EXPORT_VISIBLE_PRINTABLE_LAYERS;
generateThumbnails = false;
grayscaleBitmapCompression = BitmapCompression.AUTO_COMPRESSION;
grayscaleBitmapQuality = CompressionQuality.MAXIMUM;
grayscaleBitmapSampling = Sampling.BICUBIC_DOWNSAMPLE;
grayscaleBitmapSamplingDPI = 300;
includeBookmarks = false;
includeHyperlinks = false;
includeSlugArea = false;
includeStructure = true;
monochromeBitmapCompression = MonoBitmapCompression.CCIT4;
monochromeBitmapSampling = Sampling.BICUBIC_DOWNSAMPLE;
monochromeBitmapSamplingDPI = 1200;
omitBitmaps = false;
omitEPS = false;
omitPDF = false;
optimizePDF = true;
pageInformationMarks = false;
pageMarksOffset = 0.0833;
pdfMarkType = MarkTypes.DEFAULT_VALUE;
printerMarkWeight = PDFMarkWeight.P25PT;
registrationMarks = false;
standardsCompliance = PDFXStandards.NONE;
subsetFontsBelow = 100;
thresholdToCompressColor = 450;
thresholdToCompressGray = 450;
thresholdToCompressMonochrome = 1800;
useDocumentBleedWithPDF = false;
}
currentProcess.text = "PDF export preferences"; progressWin.show();
progressIndividual.value++; if (aProducts.length > 1) {progressOverall.value++;}
// Now let's actually set the export preferences. These are for the proof page.
with (app.pdfExportPreferences)
{
pageRange = proofRange;
useSecurity = true;
disallowChanging = true;
disallowCopying = false;
disallowDocumentAssembly = true;
disallowExtractionForAccessibility = false;
disallowFormFillIn = true;
disallowHiResPrinting = true;
disallowNotes = true;
disallowPlaintextMetadata = true;
disallowPrinting = false;
changeSecurityPassword = "sky";
if (multiColor)
{
pageRange = colorTable.toString();
}
if (currentProduct.pLabel != "")
{
pageRange += "," + labelPage.name;
}
}
currentProcess.text = "Exporting PDF proof page"; progressWin.show();
progressIndividual.value++; if (aProducts.length > 1) {progressOverall.value++;}
// Before exporting the Proof page(s), hide the color bar on multicolor products.
if (multiColor) {document.layers.item("COLOR BAR").visible = false;}
// Then we save the proof page.
document.exportFile(ExportFormat.PDF_TYPE, File(jobFolder.toString() + "/" + saveName + ".pdf"), false, tempPreset);
When that produced corrupted PDFs once in a while, I thought that perhaps it was our less-than-ideal network structure causing the problem, so I instead tried exporting the PDF file to the local hard drive rather than directly to the network, then having the file be moved to the network afterward. So, the last line in the above code block was replaced with:
// First, to the local HDD.
document.exportFile(ExportFormat.PDF_TYPE, File("~/Documents/" + saveName + ".pdf"), false, tempPreset);
$.sleep(1000);
File("~/Documents/" + saveName + ".pdf").copy(File(jobFolder.toString() + "/" + saveName + ".pdf"));
$.sleep(1000);
File("~/Documents/" + saveName + ".pdf").remove();
I even added in those 1-second delays, just in case. Sadly, this hasn't helped. I am still getting a corrupted PDF every now and then. If there is any pattern to the corrupted files, I haven't been able to discern it. Does anyone have any thoughts?
It finally hit me that, if the corrupted files are not able to be opened in Acrobat, then why not just test for that after the file is created? So I created a loop that exports the PDF file and tries to open it in Acrobat. If it opens fine, then it prints and closes the file, returning a "true" message. If it is unable to do so, then it returns a "false" message to the script. Then the loop repeats so long as that message is "false". While not a great fix for the underlying cause (whatever it may be), it at least is a workaround that will do just fine for our needs. The trick is that, because we work with Macs, we have to route the message through an AppleScript instead of using BridgeTalk to communicate directly with Acrobat.
Here's the code snippet from the main InDesign script which goes through the PDF-checking loop:
// Then we save the proof page.
// The loop is to make sure that the file was saved properly.
var validFile = false; // Flag that states whether or not the file is corrupted after saving.
var rString; // String returned from Acrobat that should be either "true" or "false".
var testAndPrintFile = File("~/Documents/testAndPrint.applescript"); // The applescript file that calls Acrobat and runs a folder-level script.
var pdfFile; // A String of the filename & path that will be passed to through the applescript file to Acrobat.
var pdfArray = new Array(4); // An array to send to Acrobat. [0] is the PDF filename as a String,
// [1] is duplex if true, [2] is the printer name, and [3] is to enable printing.
if (multiTwoSided || twoPages) pdfArray[1] = "true";
else pdfArray[1] = "false";
pdfArray[2] = localPrinter;
pdfArray[3] = "true";
while (!validFile)
{
$.writeln("If this message is seen more than once, then the Proof PDF was corrupted.");
try
{
document.exportFile(ExportFormat.PDF_TYPE, File(jobFolder.toString() + "/" + saveName + ".pdf"), false, tempPreset);
}
catch (e)
{
alert("Could not save the Proof PDF. Please close any open copies of the Proof PDF, then save and print it manually.");
}
pdfFile = jobFolder.toString() + "/" + saveName + ".pdf";
pdfArray[0] = pdfFile;
$.writeln("pdfArray contains: " + pdfArray);
try
{
rString = app.doScript(testAndPrintFile, ScriptLanguage.APPLESCRIPT_LANGUAGE, pdfArray);
validFile = rString == "true";
// validFile = true;
$.writeln("validFile is " + validFile);
if (!validFile)
{
alert("It seems that the file " + unescape(pdfArray[0]) + " is corrupted. Will try to export it again.");
}
}
catch (e)
{
$.writeln("ERROR at line number " + e.line);
$.writeln(e.description);
throw new Error("ERROR at line number " + e.line + "\n" + e.description);
}
}
The testAndPrint.applescript file that this loop calls:
set pdfFile to item 1 of arguments
set duplexed to item 2 of arguments
set printerName to item 3 of arguments
set printEnabled to item 4 of arguments
tell application "Adobe Acrobat Pro"
set result to do script ("testAndPrint(\"" & pdfFile & "\", \"" & duplexed & "\", \"" & printerName & "\", \"" & printEnabled & "\");")
end tell
return result
And, finally, the folder-level Javascript file that is loaded into memory when Acrobat starts, ready to have its function called by the above Applescript file:
var testAndPrint = app.trustedFunction(function (fName, duplexed, sPrinterName, bEnablePrinting)
{
var success = true;
app.beginPriv();
console.println("fName is " + unescape(fName));
console.println("sPrinterName is " + sPrinterName);
try
{
var printDoc = app.openDoc(unescape(fName));
var pp = printDoc.getPrintParams();
if (duplexed == "true") pp.DuplexType = pp.constants.duplexTypes.DuplexFlipLongEdge;
else pp.DuplexType = pp.constants.duplexTypes.Simplex;
pp.printerName = sPrinterName;
pp.interactive = pp.constants.interactionLevel.silent;
pp.pageHandling = pp.constants.handling.none;
if (bEnablePrinting == "true") printDoc.print({bUI: false, bSilent: true, bShrinkToFit: false, printParams: pp});
printDoc.closeDoc(true);
}
catch (e)
{
console.println("ERROR at line number " + e.lineNumber);
console.println(e.message);
success = false;
}
app.endPriv();
console.println("success is " + success);
return success;
});
I hope that, perhaps, this information might be useful to anyone else running into a similar problem. It's not pretty, of course, but it certainly gets the job done.

Server Side Logging Of Client Side Javascript Crashes

I have a large complex web app with thousands of lines of Javascript. There is a small set of intermittent Javascript bugs that are report by users.
I think these are epiphenomena of race conditions - something has not initialised correctly and the Javascript crashes causing 'down stream' js not to run.
Is there anyway to get Javascript execution crashes to log back server side?
All the js logging libraries like Blackbird and Log4JavaScript are client-side only.
I have written a remote error logging function using window.onerror as suggested by #pimvdb
Err = {};
Err.Remoterr = {};
Err.Remoterr.onerror = function (msg, errorfileurl, lineno) {
var jsonstring, response, pageurl, cookies;
// Get some user input
response = prompt("There has been an error. " +
"It has been logged and will be investigated.",
"Put in comments (and e-mail or phone number for" +
" response.)");
// get some context of where and how the error occured
// to make debugging easier
pageurl = window.location.href;
cookies = document.cookie;
// Make the json message we are going to post
// Could use JSON.stringify() here if you are sure that
// JSON will have run when the error occurs
// http://www.JSON.org/js.html
jsonstring = "{\"set\": {\"jserr\": " +
"{\"msg\": \"" + msg + "\", " +
"\"errorfileurl\": \"" + errorfileurl + "\", " +
"\"pageurl\": \"" + pageurl + "\", " +
"\"cookies\": \"" + cookies + "\", " +
"\"lineno\": \"" + lineno + "\", " +
"\"response\": \"" + response + "\"}}}";
// Use the jquery cross-browser post
// http://api.jquery.com/jQuery.post/
// this assumes that no errors happen before jquery has initialised
$.post("?jserr", jsonstring, null, "json");
// I don't want the page to 'pretend' to work
// so I am going to return 'false' here
// Returning 'true' will clear the error in the browser
return false;
};
window.onerror = Err.Remoterr.onerror;
I deploy this between the head and body tags of the webpage.
You will want to change the JSON and the URL that you post it to depending on how you are going to log the data server side.
Take a look at https://log4sure.com (disclosure: I created it) - but it is really useful, check it out and decide for yourself. It allows you to log errors/event and also lets you create your custom log table. It also allows you to monitor your logs real-time. And the best part, its free.
You can also use bower to install it, use bower install log4sure
The set up code is really easy too:
// setup
var _logServer;
(function() {
var ls = document.createElement('script');
ls.type = 'text/javascript';
ls.async = true;
ls.src = 'https://log4sure.com/ScriptsExt/log4sure.min.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ls, s);
ls.onload = function() {
// use your token here.
_logServer = new LogServer("use-your-token-here");
};
})();
// example for logging text
_logServer.logText("your log message goes here.")
//example for logging error
divide = function(numerator, divisor) {
try {
if (parseFloat(value) && parseFloat(divisor)) {
throw new TypeError("Invalid input", "myfile.js", 12, {
value: value,
divisor: divisor
});
} else {
if (divisor == 0) {
throw new RangeError("Divide by 0", "myfile.js", 15, {
value: value,
divisor: divisor
});
}
}
} catch (e) {
_logServer.logError(e.name, e.message, e.stack);
}
}
// another use of logError in window.onerror
// must be careful with window.onerror as you might be overwriting some one else's window.onerror functionality
// also someone else can overwrite window.onerror.
window.onerror = function(msg, url, line, column, err) {
// may want to check if url belongs to your javascript file
var data = {
url: url,
line: line,
column: column,
}
_logServer.logError(err.name, err.message, err.stack, data);
};
// example for custom logs
var foo = "some variable value";
var bar = "another variable value";
var flag = "false";
var temp = "yet another variable value";
_logServer.log(foo, bar, flag, temp);

FF Extension - Not Keeping Global Variable Values

I'm working on a FF extension that in short, loads dynamic images into a sidebar. The ID's that I get are from a JSON response, and are stored in a global variable declared in the same .js file as I intend to use it. My problem is when I try to simulate paging through my results. I load the sidebar using my global variable and everything is ok. When I try to then move on to the next set of images to display using the ID's i've stored in my global variable it failes due to my variable having been completely reset. I'll see if I can give a rough view of my code:
var searchVars = {
'keyword': "",
'totalResults': 0,
'imgIds': [],
'cIds': [],
'curPg': "1",
'dispStartIdx': 0,
'dispEndIdx': 4,
'dispPerPg': 5,
toString: function() {
return this.keyword + ", " +
this.totalResults + ", " +
this.imgIds + ", " +
this.cIds + ", " +
this.curPg + ", " +
this.dispStartIdx + ", " +
this.dispEndIdx + ", " +
this.dispPerPg;
}
};
var corbisquicksearch = {
onSearch: function () {
cqsearch.resetSearch(); //Resets my global variable every search
searchVars.keyword = cqsearch.getSelectedText(); //searchVars is my global variable im having trouble with
cqsearch.extendImageCache();
}
extendImageCache: function() {
var postToURL = 'http://www.agenericurl.com/Search?';
var keyword = searchVars.keyword;
var p = 1; //Page Offset for ID's returned
var size = 200; //Number of ID's returned in the response set
var query = "searchQuery=" + encodeURIComponent("q=" + keyword + "&p= " + p +"&s=" + size);
var request = new XMLHttpRequest();
request.open('post', postToURL + query, true);
request.onreadystatechange = function (aEvt) {
if (request.readyState == 4) {
alert(1);
if(request.status == 200) {
alert(2);
var responseInJSON = JSON.parse(request.responseText);
searchVars.totalResults = responseInJSON.ResultsCount;
var i = searchVars.imgIds.length;
var lastResult = i + responseInJSON.SearchResultImages.length;
while (i < lastResult) {
searchVars.imgIds[i] = responseInJSON.SearchResultImages[i].ImageId;
searchVars.cIds[i] = responseInJSON.SearchResultImages[i].CorbisId;
i++;
}
cqsearch.loadSidebar();
}
else {
dump("Error loading page\n");
}
}
};
request.send();
},
loadSidebar: function() {
//Initializing Env Variables
var sidebar = document.getElementById("sidebar");
var sidebarDoc = sidebar.contentDocument || document;
var searchInfoBox = sidebarDoc.getElementById("search_info");
var resultsBox = sidebarDoc.getElementById("img_results");
var pagingInfoBox = sidebarDoc.getElementById("paging_info");
//Loading up the search information
var searchInfo = "Displaying Results for <b>{0}<b/><br>Showing <b>{1} - {2}</b> of <b>{3}</b>";
var args = [searchVars.keyword, searchVars.dispStartIdx, searchVars.dispEndIdx, searchVars.totalResults];
var infoLbl = document.createElement("label");
infoLbl.setAttribute("value", cqsearch.strFormat(searchInfo, args));
searchInfoBox.appendChild(infoLbl);
while (resultsBox.firstChild) {
resultsBox.removeChild(resultsBox.firstChild);
}
//Loading up the image results
var i = searchVars.dispPerPg * (searchVars.curPg - 1);
var lastDisplayed = (searchVars.curPg * searchVars.dispPerPg) - 1;
alert("length" + searchVars.toString());
while (i <= lastDisplayed) {
var imageID = searchVars.imgIds[i];
var cID = searchVars.cIds[i];
var imgSrc = cqsearch.createMediaUrlParams(imageID, 'thumb', cID, false).url; //thumb, 170, hover
var img = document.createElement("image");
img.setAttribute("src", imgSrc);
alert(imgSrc);
img.setAttribute("class", "img");
var idDelimiter = "_image";
var id = cID + idDelimiter;
img.id = id;
img.addEventListener("click", function () {
cqsearch.openEnlargementPage(this.id.substring(0, this.id.indexOf(idDelimiter)));
}, false);
var imgBox = document.createElement("box");
imgBox.setAttribute("class", "imgContainer");
imgBox.appendChild(img);
resultsBox.appendChild(imgBox);
i++;
}
//Loading up paging info and functionality
var prevBtn = document.createElement("button");
prevBtn.setAttribute("label", "Previous");
prevBtn.setAttribute("oncommand", "cqsearch.prevPage()");
var nextBtn = document.createElement("button");
nextBtn.setAttribute("label", "Next");
nextBtn.setAttribute("oncommand", "cqsearch.nextPage()");
pagingInfoBox.appendChild(prevBtn);
pagingInfoBox.appendChild(nextBtn);
},
nextPage: function() {
searchVars.curPg++;
alert(searchVars.imgIds);
cqsearch.loadSidebar();
},
};
I realize its a lot of code, and I didn't post every function I have, and no, this specific URL does not work. Everything not included works fine, and does exactly what its supposed too, and nothing more which is why I left it out. But if anyone could shed some light on why my global variable is being cleared between my initial load of the sidebar, and when I click to go to the next page, I would greatly appreciate it.
If you need me to add something or clarify something please let me know and I will do so! I will probably end up sliming this code down and removing irrelevant parts.
Thanks!
If you simply want a place to store some global variables for a session, then a JavaScript Module would probably work.
Would you be able to use the client side storage to store the global variable? you will then, not lose it on page loads or refresh. You could either use this to debug and see if you are getting a page refresh because sometimes extensions are fickle and you don't even notice the refresh, but if you store the variable as a key value pair in web storage you might get past this.
localStorage.setItem('imgId', '5');
to set your key/value pair
localStorage.getItem('imgId');
to retrieve your key/value pair
Then you can set a new local storage for each series of pictures that has been displayed to the client based on the last number that is set in local storage.

Categories

Resources