Chrome Extensions "chrome.storage.local" data updating trouble - javascript

I am working on one chrome extension and i need to use local storage to send data from options page to background scritps.
Options page script:
function addToStorage(key, val){
let obj = {};
obj[key] = val;
chrome.storage.local.set( obj, function() {
if(chrome.runtime.lastError) {
console.error(
"Error setting " + key + " to " + JSON.stringify(val) +
": " + chrome.runtime.lastError.message
);
}
});
}
Background:
chrome.storage.local.get('code', function(code) {
... with code.code ...
});
For example:
Now chrome.storage.local code value is abcd
I'm performing addToStorage('code', '1234') from options page script
After that in background script value code only will change when i manually click "update" at chrome extesions page
How can i automatically get actual data at background script?

the background script will check only once when started as is.
You could pass a mesage from the options script to background scripts after you update the local storage and use that as a trigger to check storage.
try this:
Options page
function addToStorage(key, val){
let obj = {};
obj[key] = val;
chrome.storage.local.set( obj, function() {
if(chrome.runtime.lastError) {
console.error(
"Error setting " + key + " to " + JSON.stringify(val) +
": " + chrome.runtime.lastError.message
);
}
chrome.runtime.sendMessage({status: "Storage Updated"}, function (responce) {
console.log(responce);
})
});
}
Background Page:
chrome.runtime.onMessage.addListener(
function (request, sender, responce) {
if (request.status === "Storage Updated") {
chrome.storage.local.get('code', function(code) {
// ... with code.code ...
});
sendResponce({status: "Update Recieved"});
}
}
);
Hope that helps, message passing docs here: https://developer.chrome.com/extensions/messaging

Related

Angularjs problem: cannot resolve variable, but variable exists

I'm doing a project for University where I have a login for a website and I have to implement some operations. My issue is to maintain user session when a user is logged; so, if I open the website in a new tab, I want to be logged with the account of the main tab.
This is my angularjs code for the loginController:
mainAngularModule
.controller('LoginCtrl', ['$scope', '$state', 'AuthFactory',
function ($scope, $state, AuthFactory) {
let ctrl = this;
ctrl.authRequest = {username: 'admin', password: 'password'};
ctrl.doLogin = doLoginFn;
ctrl.authMessage = '';
//check if user already logged
let logSession = localStorage.getItem(("authinfo"));
if(logSession == null){
console.log("logSession null");
}
if(logSession == undefined){
console.log("isundefined");
}
if(logSession != null){
console.log("not null");
console.log("usern: " + logSession.username);
//console.log("authinfo authorities: " + logSession.authorities)
AuthFactory.setJWTAuthInfo(logSession);
$state.go("dashboard.home");
}
console.log("login authinfo: " + localStorage.getItem("authinfo"));
let sessionStorage_transfer = function(event) {
if(!event) { event = window.event; } // ie suq
if(!event.newValue) return; // do nothing if no value to work with
if (event.key === 'getSessionStorage') {
// another tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
// the other tab should now have it, so we're done with it.
} else if (event.key === 'sessionStorage' && !sessionStorage.length) {
// another tab sent data <- get it
var data = JSON.parse(event.newValue);
for (var key in data) {
sessionStorage.setItem(key, data[key]);
}
}
};
// listen for changes to localStorage
if(window.addEventListener) {
window.addEventListener("storage", sessionStorage_transfer, false);
} else {
window.attachEvent("onstorage", sessionStorage_transfer);
}
function doLoginFn() {
console.log("doLoginFn");
var requiresLogin = $state.jwtToken;
console.log("requireLogin: " + requiresLogin);
AuthFactory.sendLogin(ctrl.authRequest, successCB, errorCB);
function successCB(response) {
let authInfo = response.data;
console.log("data = " + response.data.all);
let header = response.headers();
authInfo.jwtToken = header['authorization'];
console.log("authInfo", authInfo);
// AuthFactory.user.username = authInfo.username;
// AuthFactory.user.role = authInfo.role;
let debugJWT = true;
//if (debugJWT) {
if (true) {
console.log(authInfo);
console.log("username: " + authInfo.username);
console.log("roles: " + JSON.stringify(authInfo.authorities));
console.log("jwtToken: " + authInfo.jwtToken);
console.log("userType: " + authInfo.userRole);
console.log("ended.");
}
AuthFactory.setJWTAuthInfo(authInfo);
//console.log("authinfoo1234: " + authInfo);
// localStorage.setItem("authinfo",authInfo);
console.log("authorities: " + authInfo.authorities);
$state.go("dashboard.home");
}
function errorCB(response) {
let error = response.data;
if (error && error.status === 401) {
ctrl.authMessage = error.message;
}
else {
console.error(response);
ctrl.authMessage = 'No response from server';
}
}
}
}
]);
I have a very strange problem: I'm using Intellj, and it tells me in lines
console.log("roles: " + JSON.stringify(authInfo.authorities));
console.log("userType: " + authInfo.userRole);
but if I comment lines with localStorage.setItem and localStorage.getItem, console prints on output correct userType and userRole; if I add those lines, console prints out this message:
TypeError
​
columnNumber: 17
​
fileName: "http://localhost:63342/ISSSR_frontend/app/scripts/service/AuthFactory.js"
​
lineNumber: 59
​
message: "authInfo.authorities is undefined"
I really don't understand, why it says me that it cannot resolve variable, but it can print out it?
Unfortunately I could not deploy your code would you please prepare codepen or flickr.
Some points that I can mention is below:
instead of use console.log("username: " + authInfo.username); use : console.log('username : ',authInfo.username)
Instead of JSON.stringify(authInfo.authorities) use : angular.toJson(authInfo.authorities,true)
Also console.log(response) to see what it returns.

Angular 2 - Open URL in New Window with POST

I currently have a component that requires to have a pop up upon submit. The response from the API provides a redirectURL and redirectParams to be used as the popped up window.
Simply using window.open defaults its method to GET and not POST. This causes a Not Found page whenever it is loaded this way.
This is how I currently do it:
protected makeDepositPopup(depositRequest: PaymentRequest) {
this.depositService.requestDepositPopup(depositRequest)
.subscribe(
(depositEvent: RedirectData | SuccessfulDepositPopup) => this.handleDepositPopupEvent(depositEvent),
(error: EcommError) => this.handleDepositError(error),
() => this.eventService.depositAttempt.emit()
);
}
then the event is handled via the handleDeposit event:
protected handleDepositPopupEvent(depositEvent: RedirectData | SuccessfulDepositPopup) {
if (depositEvent instanceof RedirectData) {
this.handleRedirect(depositEvent);
} else {
this.handleDepositSuccessPopup(depositEvent, this.redirectParams);
}
}
As soon as it succeeds, it then tries to open a window with the corresponding URL and parameters provided by the API response:
protected handleDepositSuccessPopup(depositEvent: SuccessfulDepositPopup, redirectParams: string): void {
redirectParams = ""; // to remove undefined value
depositEvent.params.forEach(function (data, index) {
if(index == 0) {
redirectParams += "?" + data["key"] + "=" + data["value"];
} else {
redirectParams += "&" + data["key"] + "=" + data["value"];
}
});
window.open(depositEvent.url + redirectParams);
this.router.navigate(
["deposit", this.route.snapshot.data["instrumentTypeCode"], "deposit-details", depositEvent.id], {
relativeTo: this.route.parent.parent
});
}
How do I convert this in such a way that the depositEvent.url and its appended redirectParams to open a new window with a POST method to get a successful page response?

how to show an error when in appbrowser does not load error phonegap

i am developing an application and loading an hosted application using the inapp browser plugin cordova-plugin-inappbrowser
I have gotten most of the functionalities to work but i am unable to get the part of loading an error message when he url does not load, it dosent just work and shows me an error message of the url where i have hosted my application instead.
Which could be embarrassing.
please i need help on this
This is what am working with below thanks for ur potential responses
// my child browser code, the main source of my app content
function fire(){
var ref = cordova.InAppBrowser.open('http://####################', '_blank', 'location=no,zoom=no,hardwareback=yes,clearsessioncache=yes,clearcache=no');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', inAppBrowserbLoadStart);
ref.addEventListener('loadstop', inAppBrowserbLoadStop);
ref.addEventListener('loaderror', loadErrorCallBack);
ref.addEventListener('exit', inAppBrowserbClose);
}
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage =
"alert('Sorry we cannot open that page. Message from the server is : "
+ params.message + "');"
inAppBrowserRef.executeScript({ code: scriptErrorMesssage }, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function executeScriptCallBack(params) {
if (params[0] == null) {
$('#status-message').text(
"Sorry we couldn't open that page. Message from the server is : '"
+ params.message + "'");
}
}
Your code is generally fine, but you have no control over the title of the alert() function. You can use some other techniques to display the error message. For example, you can use a div:
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage = createMsg('Sorry we cannot open that page. Message from the server is: '
+ params.message);
inAppBrowserRef.executeScript({
code: scriptErrorMesssage
}, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function createMsg(msg) {
return 'var div = document.createElement("div");'
+ 'div.style.position = "absolute";'
+ 'div.style.top = "50%";'
+ 'div.style.left = "50%";'
+ 'div.style.width = "100px";'
+ 'div.style.height = "100px";'
+ 'div.style.color = "#f00";'
+ 'div.innerHTML = "' + msg + '";'
+ 'document.appendChild(div);'
}

How to get system properties __CreatedAt, __Version in javascript backend of Azure Mobile services?

I am trying to explicitly get the system properties from my table but it is not working. I can see that the URL is returning all the data including these fields if I use https://myservice.azure-mobile.net/tables/todoitem?__systemProperties=* but on the code I cannot get it as item.__version or item.version. I have tried adding todoitemtable = WindowsAzure.MobileServiceTable.SystemProperties.All; but no success! I have also looked at http://azure.microsoft.com/en-us/documentation/articles/mobile-services-html-validate-modify-data-server-scripts/ but this is adding a new column instead of using the existing system columns.
$(function() {
var client = new WindowsAzure.MobileServiceClient('https://ib-svc-01.azure-mobile.net/', 'key');
var todoItemTable = client.getTable('todoitem');
// = WindowsAzure.MobileServiceTable.SystemProperties.All;
// Read current data and rebuild UI.
// If you plan to generate complex UIs like this, consider using a JavaScript templating library.
function refreshTodoItems() {
var query = todoItemTable.where({ complete: false });
query.read().then(function(todoItems) {
var listItems = $.map(todoItems, function(item) {
return $('<li>')
.attr('data-todoitem-id', item.id)
.append($('<button class="item-delete">Delete</button>'))
.append($('<input type="checkbox" class="item-complete">').prop('checked', item.complete))
.append($('<div>').append($('<input class="item-text">').val(item.id))
.append($('<span class="timestamp">'
+ (item.createdAt && item.createdAt.toDateString() + ' '
+ item.createdAt.toLocaleTimeString() || '')
+ '</span>')));
});
$('#todo-items').empty().append(listItems).toggle(listItems.length > 0);
$('#summary').html('<strong>' + todoItems.length + '</strong> item(s)');
}, handleError);
}
function handleError(error) {
var text = error + (error.request ? ' - ' + error.request.status : '');
$('#errorlog').append($('<li>').text(text));
}
function getTodoItemId(formElement) {
return $(formElement).closest('li').attr('data-todoitem-id');
}
// Handle insert
$('#add-item').submit(function(evt) {
var textbox = $('#new-item-text'),
itemText = textbox.val();
if (itemText !== '') {
todoItemTable.insert({ text: itemText, complete: false }).then(refreshTodoItems, handleError);
}
textbox.val('').focus();
evt.preventDefault();
});
// Handle update
$(document.body).on('change', '.item-text', function() {
var newText = $(this).val();
todoItemTable.update({ id: getTodoItemId(this), text: newText }).then(null, handleError);
});
$(document.body).on('change', '.item-complete', function() {
var isComplete = $(this).prop('checked');
todoItemTable.update({ id: getTodoItemId(this), complete: isComplete }).then(refreshTodoItems, handleError);
});
// Handle delete
$(document.body).on('click', '.item-delete', function () {
todoItemTable.del({ id: getTodoItemId(this) }).then(refreshTodoItems, handleError);
});
// On initial load, start by fetching the current data
refreshTodoItems();
});
I was trying to access the system properties from within the API scripts and found this and thought it was useful and relevant: http://www.brandonmartinez.com/2014/10/22/retrieve-system-properties-in-azure-mobile-services-javascript-backend/
Basically you can do this (example from the post):
myTable.read({
systemProperties: ['__createdAt', '__updatedAt'],
success: function(tableEntries) {
// So on and so forth
}
}

Converting an MVC4 Web API Application to Phonegap Android Application

I have an MVC4 Web API application where i have my Api Controller and Code-First EF5 database and some JavaScript functions for the functionality of my app including my Ajax Calls for my Web Api Service.I did the project on MVC because i was having trouble installing Cordova in VS2012, so i have decided to use Eclipse/Android Phonegap platform.Is there a way where i can call my web api service and be able to retrieve my database data designed EF5(MVC4) in my Android Phonegap application without having to start from the beginning the same thing again.I know phonegap is basically Html(JavaScript and Css) but i am having trouble calling my service using the same HTML markup that i used MVC4.I am a beginner please let me know if what i am doing is possible and if not please do show me the light of how i can go about this. T*his is my Html code*
<script type="text/javascript" charset="utf-8" src="phonegap-2.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="barcodescanner.js"></script>
<script type="text/javascript" language="javascript" src="http://api.afrigis.co.za/loadjsapi/?key=...&version=2.6">
</script>
<script type="text/javascript" language="javascript">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
//initialize watchID Variable
var watchID = null;
// device APIs are available
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = { timeout: 30000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
//declare a global map object
var agmap = null;
// declare zoom control of map
var zoomCtrl = null;
function initAGMap() {
agmap = new AGMap(document.getElementById("MapPanel"));
//TODO: must retrieve coords by device location not hard corded.
agmap.centreAndScale(new AGCoord(-25.7482681540537, 28.225935184269), 5); // zoom level 5 heres
// making zoom controls for map
var ctrlPos = new AGControlPosition(new AGPoint(10, 10), AGAnchor.TOP_LEFT);
zoomCtrl = new AGZoomControl(1);
agmap.addControl(zoomCtrl, ctrlPos);
}
function removeZoomCtrl()
{
zoomCtrl.remove();
}
//function search() {
// var lat = $('#latitude').val();
// var long = $('#longitude').val();
// $.ajax({
// url: "api/Attractions/?longitude=" + long + "&latitude=" + lat,
// type: "GET",
// success: function (data) {
// if (data == null) {
// $('#attractionName').html("No attractions to search");
// }
// else {
// $('#attractionName').html("You should visit " + data.Name);
// displayMap(data.Location.Geography.WellKnownText, data.Name);
// }
// }
// });
//}
//function GetCoordinate() {
//todo: get details from cordova, currently mocking up results
//return { latitude: -25.5, longitude: 28.5 };
}
function ShowCoordinate(coords) {
agmap.centreAndScale(new AGCoord(coords.latitude, coords.longitude), 5); // zoom level 5 here
var coord = new AGCoord(coords.latitude, coords.longitude);
var oMarker = new AGMarker(coord);
agmap.addOverlay(oMarker);
oMarker.show();
//todo: create a list of places found and display with marker on AfriGIS Map.
}
function ScanProduct()
{
//todo retrieve id from cordova as mockup
//This is mockup barcode
//return "1234";
//sample code using cordova barcodescanner plugin
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
//Callback function if barcodedont exist
function (error) {
alert("Scanning failed: " + error);
});
}
//Function to display Success or error in encoding.
function encode(type, data) {
window.plugins.barcodeScanner.encode(type, data, function(result) {
alert("encode success: " + result);
}, function(error) {
alert("encoding failed: " + error);
});}
function GetProductDetails(barcodeId,coords)
{
//Ajax Call to my web Api service
$.getJSON("api/products/?barcodeId=" + barcodeId + "&latitude=" + coords.latitude + "&longitude=" + coords.longitude)
.done(function (data) {
$('#result').append(data.message)
console.log(data)
var list = $("#result").append('<ul></ul>').find('ul');
$.each(data.results, function (i, item)
{
if (data.results == null) {
$('#result').append(data.message)
}
else {
list.append('<li>ShopName :' + item.retailerName + '</li>');
list.append('<li>Name : ' + item.productName + '</li>');
list.append('<li>Rand :' + item.price + '</li>');
list.append('<li>Distance in Km :' + item.Distance + '</li>');
//Another Solution
//var ul = $("<ul></ul>")
//ul.append("<li> Rand" + data.results.productName + "</li>");
//ul.append("<li> Rand" + data.results.Retailer.Name + "</li>");
//ul.append("<li> Rand" + data.results.price + "</li>");
//ul.append("<li> Rand" + data.results.Distance + "</li>");
//$("#result").append(ul);
}
});
$("#result").append(ul);
});
}
function ShowProductDetails()
{
//todo: display product details
//return productdetails.barcodeId + productdetails.retailerName + ': R' + productdetails.Price + productdetails.Distance;
}
//loading javascript api
$(function () {
initAGMap();
var coord = GetCoordinate();
ShowCoordinate(coord);
var barcodeId = ScanProduct();
var productdetails = GetProductDetails(barcodeId, coord);
ShowProductDetails(productdetails);
});
</script>
It looks like you're on the right track. The obvious error right now is that it's using a relative URL (api/products/?barcodeId=) to call the Web API. Because the HTML is no longer hosted on the same server as the Web API (even though you might be running them both on your local machine still), this won't work anymore. You need to call the service with an absolute URL (for example, http://localhost:8888/api/products/?barcodeId=).
Where is your Web API hosted right now and how are you running the Cordova code? If the Web API is up and running on your local machine and your Cordova app is running on an emulator on the same machine, you should be able to call the service by supplying its full localhost path.
If it still doesn't work, you'll need to somehow debug the code and see what the errors are.

Categories

Resources