chrome storage sync split error - javascript

Hello I am currently building a chrome extension that automates a website and on a html page I save the users checkout data using localStorage.
I then realized that you cant call local storage in a content_script
so what I did was this in the html page where I set and get the local storage.
this is what I use to save the users checkout info in the checkout html page for him to visually see and change when they want to:
var autofill = localStorage.getItem("checkout-info");
var filler = autofill.split(",");
$("#name").val(filler[0]);
$("#email").val(filler[1]);
$("#tel").val(filler[2]);
chrome.storage.sync.set({'autofiller': autofill}, function() {
});
the .val split is how I keep the data inside the inputs so the user can see it.
the chrome.storage is how I then take the data and call it later in the content_scripts file:
chrome.storage.sync.get(['autofiller'], function() {
});
checker = autofiller.split(",");
alert(checker[1], checker[2]);
and for some reason every time the alert part runs no matter what number it is it always alerts all the data not split with the commas.
Which is weird because the split works perfectly in the other file where I use localStorage.
I have also editet the file and tried this aswell:
chrome.storage.sync.set({
'info0': (filler[0])
'info1': (filler[1])
'info2': (filler[2])
'info3': (filler[3])
'info4': (filler[4])
'info5': (filler[5])
'info6': (filler[6])
'info7': (filler[7])
'info8': (filler[8])
'info9': (filler[9])
'info10': (filler[10])
'info11': (filler[11])
'info12': (filler[12])}, function() {
});
then in the content_scripts file tried this:
chrome.storage.sync.get(['info0', 'info1', 'info2', 'info3','info4','info5','info6','info7',
'info8', 'info9', 'info10', 'info11', 'info12'], function() {
});
alert(info0);
I also tried doing the set method without the () between the fillers and it also did not work. Can anyone help me Please?
Any advice on why the split isn't working?

There is a big difference between localStorage and chrome.sync: the first one is synchronous, and chrome.sync is asynchronous, which means you have to use a callback function to work with retrieved data.
It is a pretty rookie question. Please, check the answers to this question: How do I return the response from an asynchronous call?
In specifically to your case, all processing of a data should be inside the callback function:
chrome.storage.sync.get(['autofiller'], function (result) {
const checker = result.autofiller.split(',');
alert(checker[1], checker[2]);
});

Related

How to use the Firebase real time database for web application

In my website I'm Showing my database after user has given the database name, Is there any way I can constantly update the web shown databasebase without refreshing the page . I've tried using setInterval but it's not working for some reason .
function c(){
setInterval(beta, 1000);
}
function beta(){
var d = document.getElementById("opopo").value;
var firebaseRefff= firebase.database().ref('LOCATION/'+d);
firebaseRefff.on('child_added', snap=> {
var slot=snap.getKey();
var alloted=snap.child("ALLOTED").val();
var date=snap.child("DATE").val();
var limit=snap.child("LIMIT").val();
var time=snap.child("TIME").val();
$("table tbody").append(""+slot+""+alloted+""+date+""+limit+""+time+"Null");
});
}
You do not need, and should not use, setInterval to trigger the queries. What you have in your beta() function looks pretty good.
firebaseRefff.on('child_added', snap => {}) means "whenever a child is added under this location, trigger the callback function (empty in my example) with the parameter 'snap'". It will also be called once, initially, for each child that is already at that database reference location.
You need to make sure you've called beta() once to setup this trigger.
If you're still having problems, you might want to insert logging to make sure beta() is being called, what the full reference path is, if the callback is ever triggered, and if your jquery string is correct.

Wait for page load before continuing JavaScript execution

I'm new to JavaScript and trying to get this Tampermonkey script working. The scripts works just fine when it collects data from one page. However, I now want it to collect the data as before, but then move on to another page and continue the data collecting.
My code:
$(document).ready(function() {
$("#getData").click(function() {
// Part 1. Collect data and move on
window.location.href = goToURL;
// Part 2. Collect more data when the page has fully loaded
});
});
I have tired to put Part 2 of the code inside:
setTimeout(function() {
}, 5000);
and
window.onload = function(){
};
But I cannot get the code to work, it either executes before the page has loaded, or seemingly not at all. What am I missing?
When you change page with location.href, your JS is reloaded. So you need a way to store data between page changing. I suggest to use LocalStorage
Your code would look like:
function storeState(state){
localStorage.setItem('state', state);
}
function loadState(state){
return localStorage.getItem('state');
}
$(document).ready(function() {
var state = getState();
$("#getData").click(function() {
// Collect data and put it into state
storeState(/* your collected state*/)
window.location.href = goToURL;
});
});
Notice that you have to do some serialize/deserialize stuff because localStorage only save strings
Also as mentioned #charlietfl if you have different domains it will cause additional difficults

using localstorage to keep html on page refresh not working

I'm trying to integrate this fiddle: http://jsfiddle.net/jaredwilli/ReT8n/ in a fiddle I'm doing:
https://jsfiddle.net/vlrprbttst/99c8gn7k/
Basically you have a basket with some items inside of it, you can add or remove them. What I want is that, on page refresh, the html() of the .basket is kept in local storage. I'm stuck here:
https://jsfiddle.net/vlrprbttst/z8cffk4c/
I've put the forLocalStorage variable in the click handler because otherwise, the var wouldn't update itself but now I'm guessing that the final local storage code
if(localStorage.getItem('toDoData')) {
forLocalStorage = localStorage.getItem('toDoData');
}
is not working because it can't retrive the variable?
I've tried moving around things but I'm stuck here. what am i doing wrong?
You need to update DOM once your variable is set, e.g:
// LOCAL STORAGEEEEEEEE
if (localStorage.getItem('toDoData')) {
forLocalStorage = localStorage.getItem('toDoData');
$('#cart').html(forLocalStorage);
itemsCount();
}
Local storage can only store string key value pairs. I ensured you are passing in a string and also added a function to populate the cart on refresh, which resolved problems.
function populateCart() {
var items = localStorage.getItem('toDoData') || '';
$('#cart').html(items);
}
Added this call inside document.ready, like so: -
$(document).ready(function() {
populateCart();
// rest of code
});
Working CodePen: http://codepen.io/owenayres/pen/oxKmZg
You can do some light reading here on local storage. It is, in my opinion, best practice to store the data for the HTML as some JSON in local storage, which you would then loop through and regenerate the HTML for when reading this data again.

Run JQuery when data is loaded in Firebase

i have a problem that i need first to get the image links from the Firebase data base then i call a JQuery code that will organize the images in a beautiful way >> But it seems that the Jquery runs before i get the images,
Help Please ..!
JS Function
new Firebase("https://zoominp.firebaseio.com/photos/"+imageID)
.once('value', function(snap)
{
link = snap.child('imageLink').val();
link = 'images/'+link;
var id = "img";
div.innerHTML += "";
});
JQuery
jQuery("#gallery").unitegallery(
{
tiles_type:"nested",
tiles_nested_optimal_tile_width:200
});
Firebase loads (and synchronizes) the data asynchronously. So the jQuery code you have, will indeed execute before the data has come back from the server.
To fix this, move the jQuery code into the Firebase callback:
var ref = new Firebase("https://zoominp.firebaseio.com/photos/"+imageID);
ref.on('value', function(snap) {
link=snap.child('imageLink').val();
link='images/'+link;
var id="img";
div.innerHTML = div.innerHTML +"";
jQuery("#gallery").unitegallery({
tiles_type:"nested",
tiles_nested_optimal_tile_width:200
});
});
I also changed once() to on(). With that tiny change, your HTML will be updated whenever the data in the database changes. Try changing the data and you'll experience the "magic" of Firebase.
Since asynchronous loading is hard to wrap your head around when you first encounter it, I highly recommend that you read the more in-depth answers to these questions:
How do I return the response from an asynchronous call?
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
Handling Asynchronous Calls (Firebase) in functions
Returning value from a jQuery function
i have never worked with a Firebase, but you will need to have your actual resources ready before running the jQuery - you cannot do this in a synchronous way, as when you call your jquery unitedGallery it is called before the .once('value') event triggers.
do you call that new Firebase(.... thing more times in a loop or something? you could do something like keeping information about whether have all the images loaded in an array. something like this: let's assume, your images are stored in an array allOfYourImages. then,
define a global variable like this
var images_loaded=[];
for(var i=0; i<allOfYourImages.length; i++){ images_loaded[i]=false; }
then i assume you somehow iterate over your pictures since you are using imageID. add an incrementing variable var image_number=0; before the iterator and do image_number++ after each image iteration. like
var image_number=0;
...iteratorofyourchoiseihavenoideawhatareyouusing...{
new Firebase("https://zoominp.firebaseio.com/photos/"+imageID).once('value', function(snap){
...DOM stuff previously did ...
images_loaded[image_number]=true;
checkAllImagesLoaded();
});
image_number++;
}
notice the checkAllImagesLoaded() function. this will look whether have all your images already loaded and fire the jQuery gallery thing, like this
checkAllImagesLoaded(){
var all_loaded=true;
for(var i=0; i<allOfYourImages.length; i++){
all_loaded &= images_loaded[i]; //in case any of the items is false, it will set the all_loaded to false
}
if(all_loaded){
..your jQuery.("#gallery").unitegallery stuff..
}
}

Sitecore 8 Speak UI QueryDataSource in Javascript

I am trying to access QueryDatasource results in Javascript. Everything is setup correctly. I get the items by using
var destData = this.regionQueryDatasource.get("items");
My issue is that,
I want to get those items on page load. I put this code inside initialize() then it doesn't return anything. If I call it in some button click function, then it returns data.
initialized: function () {
var destData = this.regionQueryDatasource.get("items");},
I want the querying to happen in synchronous manner. Sometimes, the items are returned as empty. I want to wait till the items are loaded.
Any help would be great. Thanks in advance!
Have you tried refreshing the DataSource before calling Get items?
E.g
this.regionQueryDatasource.refresh()
Then you can check viewModel.hasItems()
Id recommend using this.regionQueryDatasource.viewModel.items() rather than this.regionQueryDatasource.get("items");

Categories