Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

set the value of a variable synchronously for an asynchronous function

function getWords( callback ){

    var words = [];

    chrome.runtime.sendMessage({detail: "words"}, function(response) {
        console.log(response) // prints ["word1, "word2" ..]
        callback(response);
    });

}



function processWords(words){
    //do your logic in here
    console.log(words);
}
getWords(processWords);

How to save Objects in local storage in Chrome + JavaScript

local storage limited to handle only string key/value pairs you can do like below using JSON.stringify and while getting value JSON.parse

var testObject = {name:"test", time:"Date 2017-02-03T08:38:04.449Z"};
Put the object into storage:

localStorage.setItem('testObject', JSON.stringify(testObject));
Or
localStorage['testObject'] = JSON.stringify(testObject));

Retrieve the object from storage:
var retrievedObject = localStorage.getItem('testObject');
Or
var retrievedObject = localStorage['testObject'];

console.log('retrievedObject: ', JSON.parse(retrievedObject));

Replace all spaces in javascript

var a = ' he l l o '
var result = a.replace(/ /g, '+');