Saving Javascript objects to Chrome.Storage - javascript

This code for a Google Chrome Extension doesn't work. I am new to Javascript and I am not sure what the problem is. Any help would be greatly appreciated.
JS/jQuery
var userV = serviceName + 'Username';
var passV = serviceName + 'Password';
boolean works = true;
var User = {
passV: password,
userV: username,
works = true;
}
chrome.storage.sync.set({User : userV}, function() {
console.log('');
});
chrome.storage.sync.set({User : passV }, function() {
console.log('');
});
Script
chrome.storage.sync.get("userV", function (User) {
sUsername = User.userV;
};
chrome.storage.sync.get("passV", function (User) {
sPassword = User.passV;
};
Thank you for any help.

In your code you are storing User and Password in the same Key Name hence you will get only Last assigned value,
as well as your retrieving the value by value not by key
JS/jQuery
var userV = serviceName + 'Username';
var passV = serviceName + 'Password';
boolean works = true;
var User = {
passV: password,
userV: username,
works = true;
}
chrome.storage.sync.set({User : userV}, function() {
console.log('');
});
chrome.storage.sync.set({Pass : passV }, function() {
console.log('');
});
Script
chrome.storage.sync.get("User", function (data) {
sUsername = data.User;
};
chrome.storage.sync.get("Pass", function (data) {
sPassword = data.Pass;
};

For more simplify, you can store the whole User object into the storage. When you want to store your user data, the code is like the following:
var userV = serviceName + 'Username';
var passV = serviceName + 'Password';
boolean worksV = true;
var user = {
password: passV,
username: userV,
works: worksV
};
chrome.storage.sync.set({"user" : user}, function() {
// Do something...
});
Then, when you want to retrieve the stored data, the code is:
chrome.storage.sync.get("user", function(data) {
var user = data.user;
var passV = user.password;
var userV = user.username;
var worksV = user.works;
// Do something...
});
I think that you don't need to store each data item as each property. I recommend that it will be stored as one object.

Related

How to call in tag manager data after user OAUTH2 authorization is complete (JavaScript)?

I've been at this all day trying to figure out how to do an XMLHTTP request after authorization but just can't for the life of me figure it out.
So far I've got the code below which authorizes the user.
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?
access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile
https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = 'NOT SHOWING FOR SECURITY REASONS';
var REDIRECT = 'NOT SHOWING FOR SECURITY REASONS'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
The code works fine as far as the login goes. It's after logging in that I don't know what to do. I've tried multiple ideas and have gotten nowhere. Any ideas on how I can call tags from tag manager in "readonly" mode after this login?
Hi I just decided to try using the JavaScript web app method and was able to get this working. If you run into the same issue using the ajax version here is the documentation! Make sure to select the JavaScript tab or you can try the oAuth2.
https://developers.google.com/identity/protocols/OAuth2UserAgent

Download data as Excel file using web api and angular JS

I have a scenario to download file from the web app that uses a) Angular JS as front end b) Web api as server and the browser is IE9.
I have tried lot of plugins for converting HTML table to excel,csv but none of them worked for IE9.So i have decided generate the file in web api and download in the client.But that too does not work.
Can any one share an working example for this scenario ?
Angular JS Code:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, exportToExcelService) {
$scope.export = function () {
exportToExcelService.download().success(
function (response) {
})
.error(function (response, status) {
});
}
}).
factory('exportToExcelService', function ($http) {
var sampleAPI = {};
sampleAPI.download = function () {
return $http({
method: 'POST',
url: 'api/Sample/download'
});
}
return sampleAPI;
});
Web APi Controller code:
[HttpPost]
public HttpResponseMessage download()
{
List<Record> obj = new List<Record>();
obj = RecordInfo();
StringBuilder str = new StringBuilder();
str.Append("<table border=`" + "1px" + "`b>");
str.Append("<tr>");
str.Append("<td><b><font face=Arial Narrow size=3>FName</font></b></td>");
str.Append("<td><b><font face=Arial Narrow size=3>LName</font></b></td>");
str.Append("<td><b><font face=Arial Narrow size=3>Address</font></b></td>");
str.Append("</tr>");
foreach (Record val in obj)
{
str.Append("<tr>");
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.FName.ToString() + "</font></td>");
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.LName.ToString() + "</font></td>");
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.Address.ToString() + "</font></td>");
str.Append("</tr>");
}
str.Append("</table>");
HttpResponseMessage result = null;
// serve the file to the client
result = Request.CreateResponse(HttpStatusCode.OK);
byte[] array = Encoding.ASCII.GetBytes(str.ToString());
MemoryStream mem = new MemoryStream(array);
result.Content = new StreamContent(mem);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Data.xls"
};
return result;
}
public List<Record> RecordInfo()
{
List<Record> recordobj = new List<Record>();
recordobj.Add(new Record { FName = "Smith", LName = "Singh", Address = "Knpur" });
recordobj.Add(new Record { FName = "John", LName = "Kumar", Address = "Lucknow" });
recordobj.Add(new Record { FName = "Vikram", LName = "Kapoor", Address = "Delhi" });
recordobj.Add(new Record { FName = "Tanya", LName = "Shrma", Address = "Banaras" });
recordobj.Add(new Record { FName = "Malini", LName = "Ahuja", Address = "Gujrat" });
recordobj.Add(new Record { FName = "Varun", LName = "Katiyar", Address = "Rajasthan" });
recordobj.Add(new Record { FName = "Arun ", LName = "Singh", Address = "Jaipur" });
recordobj.Add(new Record { FName = "Ram", LName = "Kapoor", Address = "Panjab" });
return recordobj;
}
I found the solution by using the following code and it works like a charm.We just need to add window.location.href.
app.controller('myCtrl', function ($scope, exportToExcelService,$location) {
$scope.export = function () {
exportToExcelService.download().success(
function (response) {
window.location.href = 'api/sample/download'
})
.error(function (response, status) {
var str = 'Hello'
});
}
}).

How do I define and receive data from multiple WebSockets in JavaScript?

I have the following code snippet which I need to extend to define multiple WebSockets and I am clueless as to how do I go about it:
var registerWebSocketHandlers = function(webSocket) {
webSocket.onclose = function(){
setTimeout(service.reopen, reconnectTimeout *= 2);
};
webSocket.onopen = function(e) {
icc.publish('webSocket.reconnect');
reconnectTimeout = defaultReconnectTimeout; //reset this
deferredSend();
};
webSocket.onerror = function(e) {
throw new Error("[WebSocket] An error occured " + e);
};
}
var openConnection = function() {
connectionWasOpenBefore = true;
webSocket = new $window.WebSocket(xyz);
webSocket.id = uniqid();
registerWebSocketHandlers(webSocket);
};
var uniqid = function() {
return (new Date().getTime()).toString(16);
}
service.setMessageEventHandler = function(cb) {
webSocket.onmessage = function(msg) {
if(msg.data.indexOf('Status: connected') === 0)
{
return;
}
var jsonObj = JSON.parse(msg.data);
cb(jsonObj);
};
};
How do I twist the code to suit the needs of multiple WebSockets and attaching the appropriate callback to it?
Use the multiton pattern.
var socketFactory = module.factory('SocketFactory', function($rootScope){
var factory = {};
var instances = {};
factory.getInstance = function(name, config){
if(!(name in instances)){
instances[name] = createNewWebSocketInstance(name, config);
}
return instances[name];
};
var createNewWebSocketInstance = function(name, config){
var webSocket = new $window.WebSocket(config.address);
webSocket.id = uniqid();
registerWebSocketHandlers(webSocket, name, config.handlers); //etc.
return webSocket;
};
var registerWebSocketHandlers = function(webSocket, name, handlers){
webSocket.onmessage = function(event){
$rootScope.$emit('SocketMessageReceived_' + name, event.data);
};
//etc...
};
return factory;
});
This will separate your different websockets by name. Use getInstance('whatever') to get a websocket labelled as 'whatever'.
var firstConfig = {url: '*****', username: '****', password: '****', etc: '****'};
// You only need to pass in the config the first time.
var firstWebSocket = SocketFactory.getInstance('firstSocket', firstConfig);
var secondConfig = {url: '####', username: '####', password: '####', etc: '####'};
var secondWebSocket = SocketFactory.getInstance('secondSocket', secondConfig);
Next, from any other area you can access the configured websockets by their instance names.
var firstWebSocket = SocketFactory.getInstance('firstSocket');
// It would probably be a good idea to add this listener in the SocketFactory instead and broadcast an event when there's a message so multiple listeners can respond to it.
firstWebSocket.onmessage = function(){...};
var secondWebSocket = SocketFactory.getInstance('secondSocket');
secondWebSocket.onmessage = function(){...};

Using parse.com is it possible to convert a string so that it saves as a pointer in the object browser?

Using parse.com and JavaScript.
Currently I have a BadgeSentTo which is a string taken from a html option box. I want to save this to parse, but ideally I want to save it into a pointer column "SentTo" so that it links back to the _User class.
It wont let me save as is, because its expecting a pointer. Is there a why to convert this to a pointer in the code?
$(document).ready(function () {
$("#send").click(function () {
var myBadge = new MyBadge();
var badgeselected = $('#badgeselect img').attr("src");
var BadgeSentTo = $('#SentToUser').val();
var uploadercomment = $('#UploaderComment').val();
myBadge.set("BadgeName", badgeselected);
myBadge.set("Comment", uploadercomment);
myBadge.set("uploadedBy", Parse.User.current());
myBadge.set("SentTo", BadgeSentTo).id;
myBadge.save(null, {
success: function (results) {
console.log("Done");
//location.reload();
},
error: function (contact, error) {
// The save failed.
alert("Error: " + error.code + " " + error.message);
}
});
return false;
});
});
The query capturing the data is
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var query = new Parse.Query(FriendRequest);
query.include('toUser');
query.include('SentTo');
query.include("myBadge");
query.equalTo("fromUser", currentUser);
query.equalTo("status", "Request sent");
query.find({
success: function (results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').id
});
var select = document.getElementById("selectNumber");
$.each(friends[0], function (i, v) {
//alert(i+" "+v);
var opt = v;
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
})
}
If BadgeSentTo contains the objectId of the User, you'll need to wrap that in a Parse Object. The SDK will convert it to a pointer to _User when it saves.
myBadge.set("SentTo", new Parse.User({id: BadgeSentTo}));

Getting undefined when database is empty

Im having a problem with my mobile app i do not know how to solve it.
when i push a button that gets data from a database, i parse it in json and when i want to use it in my app i get the undefined. Hoe can i make it so i do not get the undifined.
Note
I only get the undefind when the database is empty.
This is the code that i use
subjectButton.addEventListener('click', function(e) {
Subjects.getSubjects(url, function(response) {
if(response == '') {
alert('There where no subjects found');
} else {
subjectView.remove(subjectsLabel);
var data = JSON.parse(response);
if(data != 'undefined') {
var subjectNameButton = [];
var subjectEditButton = [];
var subjectDeleteButton = [];
for(i in data) {
id = data[i].id;
var subject = data[i].subject;
var year = data[i].year;
var status = data[i].status;
var color;
Ti.API.info('id: ' + id);
Ti.API.info('type id: '+ typeof id);
Can someone explain to me how i can make it so i don't get the undefined
Like #0101 said json can't return undefined so your problem is somewhere else.
I know this is not the best solution but it seems to work for me:
subjectButton.addEventListener('click', function(e) {
Subjects.getSubjects(url, function(response) {
if(response == '') {
alert('There where no subjects found');
} else {
subjectView.remove(subjectsLabel);
var data = JSON.parse(response);
var subjectNameButton = [];
var subjectEditButton = [];
var subjectDeleteButton = [];
for(i in data) {
id = data[i].id;
var subject = data[i].subject;
var year = data[i].year;
var status = data[i].status;
var color;
Ti.API.info('id: ' + id);
if(id != undefined) {
//Your code here
} else {
alert('There where no subjects found');
}
}
}
});
});
So here you have a check if one of the variables returns undefined or not. If it isn't undefined it will run your code else it will give you / the user an alert message
You will never get "undefined" from JSON.parse. The error must occurred somewhere else. Try this:
Subjects.getSubjects(url, function(response) {
if(!response) {
alert('There where no subjects found');
}
else {
subjectView.remove(subjectsLabel); // You probably should move this after JSON.parse
try {
var data = JSON.parse(response),
subjectNameButton = [],
subjectEditButton = [],
subjectDeleteButton = [];
for (i in data) { // Global i?
id = data[i].id; // Global too?
var subject = data[i].subject;
var year = data[i].year;
var status = data[i].status;
var color;
Ti.API.info('id: ' + id);
Ti.API.info('type id: '+ typeof id);
// ...
}
}
catch(e) {
console.log("Invalid JSON")
};
// ...
}
}

Categories