localStorage Not Clearing in Any Browser Outside of Chrome - javascript

I'm having an issue when it comes to the localStorage clearing in any browser environment outside of Chrome. I have a captcha using shapes that the user must draw to submit a form. There is a span the user can click to generate a new shape. In order to keep the information inputted into the previous fields, I store the data in localStorage every time a new shape is requested. However, if the page is refreshed, I'd like the localStorage to be completely wiped out.
Here is the code for the span that the user clicks on:
<span style="color:#0000EE;cursor:pointer;" id="new-shape" onclick="window.location.reload()" title="Click for a new shape">new shape</span>
And here is the JS for the localStorage:
$('#new-shape').on('click', function () {
var stickies = $('.sticky');
var dropdowns = $('select');
window.onbeforeunload = function () {
localStorage.setItem("branch", $('#00NL0000003INTJ').val());
localStorage.setItem("department", $('#00NL0000003I0Ux').val());
localStorage.setItem("contact", $('#00NL0000003INUC').val());
localStorage.setItem("company", stickies[0].value);
localStorage.setItem("firstName", stickies[1].value);
localStorage.setItem("lastName", stickies[2].value);
localStorage.setItem("phone", stickies[3].value);
localStorage.setItem("ext", stickies[4].value);
localStorage.setItem("email", stickies[5].value);
localStorage.setItem("help", stickies[6].value);
}
});
window.onload = function () {
var stickies = $('.sticky');
var dropdowns = $('select');
var selects = [localStorage.getItem("branch"), localStorage.getItem("department"), localStorage.getItem("contact")];
var company = localStorage.getItem("company");
var first = localStorage.getItem("firstName");
var last = localStorage.getItem("lastName");
var phone = localStorage.getItem("phone");
var ext = localStorage.getItem("ext");
var email = localStorage.getItem("email");
var help = localStorage.getItem("help");
var stickiesArr = [company, first, last, phone, ext, email, help];
for (var i = 0; i < stickiesArr.length; i++) {
if (stickiesArr[i] != null) {
stickies[i].value = stickiesArr[i];
}
}
for (var i = 0; i < selects.length; i++) {
if (selects[i] != null) {
dropdowns[i].value = selects[i];
}
}
//this allows the wipe out of all data on a page refresh,
//but clicking on "new shape" will maintain the data
localStorage.clear();
}
This code works flawlessly in Chrome, but the page refresh in IE and Firefox fails to clear the localStorage. Am I doing something wrong for the localStorage to clear across multiple browsers?
Edit
I have tried using window.location.clear(), and for good measure, localSession.clear().

I managed to finally get it to work. Part of the problem was the call of:
window.onbeforeunload = function () { (...) }
FireFox and IE11 both were having trouble with this anonymous function call. I had to change my on.click event to:
$('#new-shape').on('click', function () {
var stickies = $('.sticky');
localStorage.setItem("branch", $('#00NL0000003INTJ').val());
localStorage.setItem("department", $('#00NL0000003I0Ux').val());
localStorage.setItem("contact", $('#00NL0000003INUC').val());
localStorage.setItem("company", stickies[0].value);
localStorage.setItem("firstName", stickies[1].value);
localStorage.setItem("lastName", stickies[2].value);
localStorage.setItem("phone", stickies[3].value);
localStorage.setItem("ext", stickies[4].value);
localStorage.setItem("email", stickies[5].value);
localStorage.setItem("help", stickies[6].value);
});
And my window.onload anonymous function call had to be slightly reconfigured to:
window.onload = function () {
var stickies = $('.sticky');
var dropdowns = $('select');
var selects = [localStorage.getItem("branch"), localStorage.getItem("department"), localStorage.getItem("contact")];
var company = localStorage.getItem("company");
var first = localStorage.getItem("firstName");
var last = localStorage.getItem("lastName");
var phone = localStorage.getItem("phone");
var ext = localStorage.getItem("ext");
var email = localStorage.getItem("email");
var help = localStorage.getItem("help");
var localStorageArr = [company, first, last, phone, ext, email, help];
//input fields sticky
for (var i = 0; i < localStorageArr.length; i++) {
stickies[i].value = localStorageArr[i];
}
//dropdown fields sticky
for (var i = 0; i < selects.length; i++) {
if (selects[i] != null) {
dropdowns[i].value = selects[i];
} else {
dropdowns[i].selectedIndex = 0;
}
}
//fixing textarea
if (help === null) {
stickies[6].value = "";
}
localStorage.clear();
}
Some hacky workarounds, but the results are now working as desired.

Related

refresh drop down list after button click in web app

I have a web app with one drop down list and 2 buttons. The drop down list get values from a sheet. The buttons write back in the sheet. The script I have works fine with that:
<script>
$(function() {
$('#txt1').val('');
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
});
function updateSelect(opt)
{
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<opt.length;i++)
{
select.options[i] = new Option(opt[i],opt[i]);
}
}
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
}
}
document.getElementById("but1").addEventListener("click",listS);
function yourCallBack(response) {
}
</script>
In Java script:
function getSelectOptions()
{
var ss=SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh=ss.getSheetByName('Database');
var rg=sh.getRange(2,1,sh.getLastRow()-1,8);
var vA=rg.getValues();
var useremail = Session.getActiveUser().getEmail();
var opt=[];
for(var i=0;i<vA.length;i++)
{
if(vA[i][1] == "Pending Approval"){
if(vA[i][7]+"#xxx.com" == useremail || vA[i][7]+"#xxx.com" == useremail) {
opt.push(vA[i][3]+" REQ ID: "+vA[i][0]);
}
}
};
if (opt.length == 0) {opt.push("You do not have pending requests")};
return opt;
}
function doGet() {
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
}
function yourServerSideFunc(body) {
var value = body["value"];
var ss = SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh = ss.getSheetByName('Database');
var rg=sh.getRange(1,1,sh.getLastRow()-1,4);
var vA=rg.getValues();
var str = "Approved";
for(var i=0;i<vA.length;i++)
{
if(vA[i][3]+" REQ ID: "+vA[i][0] == value) {
sh.getRange(i+1, 2).setValue(str);
}
};
return ContentService.createTextOutput(JSON.stringify({message: "ok"})).setMimeType(ContentService.MimeType.JSON);
Now I am trying to regenerate the drop down list values after the button is clicked. I tried to add
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
in yourServerSideFunc(body) function to regenerate the HTML but does not work. I have tried to force a HTML refresh, but also did not work.
How can I easily re-trigger the generation of the drop down list items? Worst case scenario it is ok to refresh the whole page, but it should be simple to regenerate the drop down list since I have already the code for it.
I ended up with this work around.
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
//ADDED:
var select = document.getElementById("sel1");
select.options[index] = new Option("Approved! Please refresh","Approved! Please refresh");
selectElem.selectedIndex = index;
}
}
It does not really meet the original goal to refresh the list from the sheet. It would be great if someone else posted a solution to call the server function. I tried to add google.script.run.doGet() and similar, but it seems that it does not call the server side functions properly.

Why searchbox become lagging when typing word to search data in CSV?

I developed the store locator using open street map and leaflet. The problem is when I want to type in searchbox it will become lagging to finish the word. That store locator read from the CSV file that has 300++ data. Below is the code for the searchbox:
var locationLat = [];
var locationLng = [];
var locMarker;
var infoDiv = document.getElementById('storeinfo');
var infoDivInner = document.getElementById('infoDivInner');
var toggleSearch = document.getElementById('searchIcon');
var hasCircle = 0;
var circle = [];
//close store infor when x is clicked
var userLocation;
$("#infoClose").click(function() {
$("#storeinfo").hide();
if (map.hasLayer(circle)) {
map.removeLayer(circle);
}
});
var listings = document.getElementById('listingDiv');
var stores = L.geoJson().addTo(map);
var storesData = omnivore.csv('assets/data/table_1.csv');
function setActive(el) {
var siblings = listings.getElementsByTagName('div');
for (var i = 0; i < siblings.length; i++) {
siblings[i].className = siblings[i].className
.replace(/active/, '').replace(/\s\s*$/, '');
}
el.className += ' active';
}
function sortGeojson(a,b,prop) {
return (a.properties.name.toUpperCase() < b.properties.name.toUpperCase()) ? -1 : ((a.properties.name.toUpperCase() > b.properties.name.toUpperCase()) ? 1 : 0);
}
storesData.on('ready', function() {
var storesSorted = storesData.toGeoJSON();
//console.log(storesSorted);
var sorted = (storesSorted.features).sort(sortGeojson)
//console.log(sorted);
storesSorted.features = sorted;
//console.log(storesSorted)
stores.addData(storesSorted);
map.fitBounds(stores.getBounds());
toggleSearch.onclick = function() {
//var s = document.getElementById('searchbox');
//if (s.style.display != 'none') {
//s.style.display = 'yes';
//toggleSearch.innerHTML = '<i class="fa fa-search"></i>';
//$("#search-input").val("");
//search.collapse();
//document.getElementById('storeinfo').style.display = 'none';
//$('.item').show();
//} else {
//toggleSearch.innerHTML = '<i class="fa fa-times"></i>';
//s.style.display = 'block';
//attempt to autofocus search input field when opened
//$('#search-input').focus();
//}
};
stores.eachLayer(function(layer) {
//New jquery search
$('#searchbox').on('change paste keyup', function() {
var txt = $('#search-input').val();
$('.item').each(function() {
if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1) {
$(this).show();
} else {
$(this).hide();
}
});
});
I dont know what is the cause of the lag in the search box. It is something wrong in code or the csv file? Thank you
Every iteration of $('.item').each is causing a layout change because $(this).hide() or $(this).show() causes the item to removed/added to the DOM as the style is set to display:none back and forth. DOM manipulations and the corresponding layout changes are expensive.
You can consider accumulating the changes and doing one batch update to the DOM using a function like appendChild

Win Pivot App. Need to access some data from a section. Any ideas?

I have a JavaScript Win Pivot Application
Into the Hub I am retrieving some information:
function initPages(options) {
for (var i = 0; i < options.length ; i++) {
var menuItem = options[i];
menuItem.showBanner = (i == 0);
definePages(options);
}
}
and in a .Js file I have the definePages function created:
functions.js:
function definePages(item) {
var action = item[0];
var animation = item[1];
var scyfy = item[2];
var localmovies = item[3];
var clasic = item[4];
var comedy = item[5];
var biography = item[6];
var drama = item[7];
var kids = item[8];
var musical = item[9];
var romantic = item[10];
var suspense = item[11];
var horror = item[12];
var art = item[13];
var personalities = item[14];
var history = item[15];
var society = item[16];
}
Now, in my section 1 I initialize the page by calling another function there:
ready: function (element, options) {
// TODO: Inicializar la página aquí.
options = options || {};
initMovies();
},
function initMovies() {
var element = document.getElementById("movieContainer");
//var movies = ??????????????????????????
//console.log(movies);
//it keeps going
}
I need to be able to retrive, in that var movies, the var action, from the functions.Js or, which is the same, the items[0]...
However, if I call a function in functions.Js, which is defined in section1Page, it won´t work...
I can call functions and pass data from anywhere to functions.Js, but not the other way around...
Any ideas on what should I do? Thanks!!!
I fixed it... I created a global var in function.Js and I get the info from the array in each section later on:
function definePages(item) {
tooSleepyToThink = item;
}
section1Page:
function initMovies() {
var elemento = document.getElementById("movieContainer");
console.log(tooSleepyToThink[0].text);
}

How to find the number of form elements that are getting passed to e.parameter in GAS?

In Google App Scripts (GAS), I want to be able to add and remove TextBox and TextArea elements to a FlexTable (that's being used as a form) and not worry about how many there are. I've named the text elements based on a counter to make this process easier.
So, is there a way to get the number of inputs (TextBox + TextArea) passed to e.parameter after the form is submitted?
Here's the relevant code from the FlexTable:
function doGet() {
var app = UiApp.createApplication();
var flex = app.createFlexTable().setId('myFlex');
var counter = 0;
var row_counter = 0;
...
var firstnameLabel = app.createLabel('Your FIRST Name');
var firstnameTextBox = app.createTextBox().setWidth(sm_width).setName('input' + counter).setText(data[counter]);
flex.setWidget(row_counter, 1, firstnameLabel);
flex.setWidget(row_counter, 2, firstnameTextBox);
row_counter++;
counter++;
var lastnameLabel = app.createLabel('Your LAST Name');
var lastnameTextBox = app.createTextBox().setWidth(sm_width).setName('input' + counter).setText(data[counter]);
flex.setWidget(row_counter, 1, lastnameLabel);
flex.setWidget(row_counter, 2, lastnameTextBox);
row_counter++;
counter++;
...
var submitButton = app.createButton('Submit Proposal');
flex.setWidget(row_counter, 2, submitButton);
var handler = app.createServerClickHandler('saveProposal');
handler.addCallbackElement(flex);
submitButton.addClickHandler(handler);
var scroll = app.createScrollPanel().setSize('100%', '100%');
scroll.add(flex);
app.add(scroll);
return app;
}
And here's the code for the ClickHandler (notice that I currently have 39 elements in my FlexTable):
function saveProposal(e){
var app = UiApp.getActiveApplication();
var userData = [];
var counter = 39;
for(var i = 0; i < counter; i++) {
var input_name = 'input' + i;
userData[i] = e.parameter[input_name];
}
So, is there a way to get the number of elements (in this case 39) without manually counting them and assigning this value to a variable?
I'm new at this stuff and I'd appreciate your help.
Cheers!
The simplest way is to add a hidden widget in your doGet() function that will hold the counter value like this :
var hidden = app.createHidden('counterValue',counter);// don't forget to add this widget as a callBackElement to your handler variable (handler.addCallBackElement(hidden))
then in the handler function simply use
var counter = Number(e.parameter.counterValue);// because the returned value is actually a string, as almost any other widget...
If you want to see this value while debugging you can replace it momentarily with a textBox...
You can search for arguments array based object.
function foo(x) {
console.log(arguments.length); // This will print 7.
}
foo(1,2,3,4,5,6,7) // Sending 7 parameters to function.
You could use a while loop.
var i = 0;
var userData = [];
while (e.parameter['input' + i] != undefined) {
userData[i] = e.parameter['input' + i];
i++;
};
OR:
var i = 0;
var userData = [];
var input_name = 'input0';
while (e.parameter[input_name] != undefined) {
userData[i] = e.parameter[input_name];
i++;
input_name = 'input' + i;
};

Dynamically Change Option Set Values in CRM

I am using CRM Online 2013.
I am trying to remove 3 values from an optionset under a certain condition.
The optionset has six options by default: they are listed at the top of my JS code below.
When I run my code, the correct amount of options appear; but they all say undefined.
Here is what I have at the moment:
var customer = 100000000;
var partner = 100000001;
var partnerCustomer = 100000002;
var customerAndBeta = 100000003;
var partnerAndBeta = 100000004;
var partnerCustomerAndBeta = 100000005;
function populateBetaOptionSet(beta) {
var options = Xrm.Page.getAttribute("intip_websiteaccess").getOptions();
var pickListField = Xrm.Page.getControl("intip_websiteaccess");
for(i = 0; i < options.length; i++)
{
pickListField.removeOption(options[i].value);
}
if (beta == false) {
pickListField.addOption(customer);
pickListField.addOption(partner);
pickListField.addOption(partnerCustomer);
}
pickListField.addOption(customerAndBeta);
pickListField.addOption(partnerAndBeta);
pickListField.addOption(partnerCustomerAndBeta);
}
This is being called from another function which is wired up to a separate field's onchange event. I am sure this is working correctly as I am getting the correct beta value through when it is called.
I am removing all the options before re-adding them to avoid duplicates.
Any idea what I am doing wrong here/or know of a better way of doing this?
Re-wrote your function to match the criterion. The option is an object with both text and value. This is why you see undefined (missing text);
So instead of
var customer = 100000000
it needs to be
var customer = { value : 100000000 , text : "Customer" };
The code below saves each option in global scope and uses it each time you call populateBetaOptionSet
function populateBetaOptionSet(beta) {
var xrmPage = Xrm.Page;
var pickListField = xrmPage.getControl("intip_websiteaccess");
var options = pickListField.getOptions();
//save all options
if (!window.wsOptions)
{
window.wsOptions = {};
wsOptions.customer = pickListField.getOption(100000000);
wsOptions.partner = pickListField.getOption(100000001);
wsOptions.partnerCustomer = pickListField.getOption(100000002);
wsOptions.customerAndBeta = pickListField.getOption(100000003);
wsOptions.partnerAndBeta = pickListField.getOption(100000004);
wsOptions.partnerCustomerAndBeta = pickListField.getOption(100000005);
}
//clear all items
for(var i = 0; i < options.length; i++)
{
pickListField.removeOption(options[i].value);
}
if (beta == false) {
pickListField.addOption(wsOptions.customer);
pickListField.addOption(wsOptions.partner);
pickListField.addOption(wsOptions.partnerCustomer);
}
pickListField.addOption(wsOptions.customerAndBeta);
pickListField.addOption(wsOptions.partnerAndBeta);
pickListField.addOption(wsOptions.partnerCustomerAndBeta);
}
Example use Xrm.Page.getControl(..).addOption :
var low = {value : 100000000, text : "Low"};
var medium = {value : 100000001, text : "Medium"};
var high = {value : 100000002, text : "High"};
var pickList = Xrm.Page.getControl("control_name");
var options = pickList.getOptions();
for (var i = 0; i < options.length; i++)
pickList.removeOption(options[i].value);
pickList.addOption(low);
pickList.addOption(medium);
pickList.addOption(high);

Categories