Chrome extension data connection to server - database

I would like to connect my Chrome Extension to my server, and send data back and forth. In particular, when the user clicks a button on the extension when he's navigating a certain URL, the server checks its database to see how many times that URL has been clicked, increment the count, and send the new count back to the user.
I know that sending the data to the server is possible with an AJAX request, but what about getting the data back from the server?

I think, you may use AJAX for getting updated count in a straightforward manner. For example (with jQuery):
$.ajax({
url: 'ajax/count.php?url=' + encodeURIComponent(newURL),
// dataType: 'json',
success: function(data) {
// parse you data received from server here
// data.count
}
});
So you can "send" new info as parameters of GET request, and get required information from server as http-response. The type of the data used to transfer the count is up to you. For example, this can be json (jQuery provides a shorthand method getJSON, which does the same customized ajax call).
If you don't want GET, you may use POST and specify data as follows:
$.ajax({
type: "POST",
url: "ajax/count.php",
data: { url: newURL },
success: function(data){
// ...
}
});

You will obviously need to use xhr / ajax
But with the present chrome-extension API you might get an error like this
No 'Access-Control-Allow-Origin' header is present on the requested resource.
In order to get around this problem one can simply put the link to the server on the permission array in manifest.json
"permissions": [
"tabs",
"http://www.myserver.dom"
],
For more detailed description see this documentation by Google

Related

How to attach an Authorization header with a token when using Leaflet js

I am using Leaflet in my Angular.js map application. One of my resources requires an authorization header with token. I am using the leaflet-realtime plugin (found here: https://github.com/perliedman/leaflet-realtime) to get map updates and therefore need to be able to specify my header when realtime performs a fetch to get the data.
I first tried using another library, fetch-intercept (found here: https://github.com/werk85/fetch-intercept), to intercept the requests and attach the header, but the interceptor was being ignored. I included a console.log in the interceptor and it was never reached.
After more research, I noticed specifying headers is supposed to be supported: https://github.com/perliedman/leaflet-realtime/pull/83. However, I cannot find an example for how to properly attach an authorization token. Here is what I am currently trying:
this.mapRealtime = L.realtime({
url: this.getRealtimeUrl(),
crossOrigin: true,
headers: {"Authorization": "token"},
type: 'json',
},
However, when I check the Network logging from my web browser (Chrome) debugging console, all I see for the Request Headers is:
Provisional headers are shown
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
and the server returns status 403 with errortype MissingAuthenticationTokenException.
Can anyone provide an example of how to correctly attach the token? Thanks!
The realtime Leaflet only take url or json file path and you will be unable to pass headers(auth) as they have patch for it which is not working. I was facing same issue. What I did is following:
realtime = (L as any).realtime(async function (success, error) {
let geodataJson = await self.updateGeoJson();
success(geodataJson);
}, {
interval: 15 * 1000,
onEachFeature: onEachFeature,......
I have pass funtion to realtime and in that function I called simple API with headers
async updateGeoJson() {
await this.api.getMarkersGeoJson().subscribe((res: any) => {
this.geoData = res;
});
return this.geoData; }
On first call it will not get data in from this function so we also need to load data in this.geoData in ngOnInit before initmap.
For me it is working I know this is just work around but this issue is still in leaflet realtime. Hopefully this will work for you

2 queries on loading webpage blocking each other

I am making a webpage which on load makes 2 queries. However, results of both queries are coming at same time (the longer time) because one is blocking the other. Is there a way i can give a time delay so the other query is made only after the data from first query is loaded ?
Although the information you are providing are not sufficient, I am assuming you are making Ajax requests using Javascript. If that is the case you can use jQuery in order to have some code that will run only after the request answer is received (it might have an error)
$.ajax({
url: "URL for first request here",
method: 'Your request method (POST, GET etc)',
data: 'Here assign any data you need to send'
})
.done(function( data ) {
// This code will be called only if your request is successful
// data is the response from the server
// Perform 2nd Request
$.ajax({
url: "URL for second request here",
method: 'Your request method (POST, GET etc)',
data: 'Here assign any data you need to send'
})
.done(function( data ) {
})
.fail(function(){
});
})
.fail(function(){
// This code will be called only if your request fails
});

AngularJS load data from server

I have the following scenario, a page that will show different widgets with different data, the back-end is ASp.NET Web API 2 with SQL Server and EF + Repository Pattern + Unit Of Work.
If I have to show quite some data, including user profile and other information on top of the widgets information, what will you recommend:
make one big $http.get request that will return a big json and bind that one to the UI
or
each controller (service) when it loads will make it's unique call to back-end and get's the data it needs to display, that means each widget will make a call to back-end and retrieve it's values.
I just want to know what do you recommend as a best practice.
IMHO the best way is to separate every request into single service methods that way you can reuse just a part of it and not make server calls to load to whole data, check the angular-resource $resource to have a clean reusable service of server calls and not a bunch of $https arround your code:
example:
A service that points some url of your backend server
.factory('ClientService', ['$resource', function($resource){
return $resource('http://some_url/:controller/:method', null, {
"agents": { method: 'GET', params: { controller: 'agent', method: 'search' }, cache: false },
"query": { method: 'GET', params: { controller: 'client', method: 'search' }, cache: false },
"save": { method: 'POST', params: { controller: 'client', method: 'save' } },
"delete": { method: 'POST', params: { controller: 'client', method: 'delete' } }
})
}])
The use in the controller (Injecting ClientService as dependency)
// If i want to query the agents into a scope element
// that will call the url = http://some_url/agent/search
$scope.agents = ClientService.agents();
// If i want to query a single client i cant send adtional params
// as is a get request it will call http://some_url/client/search?id=5
$scope.client = ClientService.query({id:5});
// and you can event manage callbacks if you want to
// This will send the client object to the url = http://some_url/client/save
ClientService.save($scope.client).$promise.then(function(response){ alert(response) })
As you can see this way you can access just the things you need from the backend server not having to do all the callback response if you dont need to and in a reusable cleaner way
Info Angular Resource Docs
I think it depends...
If performance might be a problem you should think about what is best for your User... Will the overhead of making 4 HTTP requests affect the user experience in anyway? Also, would a one big request take too much time to retrieve info from the database?
However if you want just to use a developer perspective of the problem, I'd prefer doing 1 generic API call then calling it 4 times in Angular with different parameters for each Widget.
It is likely that making 4 requests will actually be faster. Not to mention the data can start being populated on the screen as it comes back, instead of needing to wait for the slowest service.
For the max number of concurrent AJAX requehttp://www.coderanch.com/t/631345/blogs/Maximum-concurrent-connection-domain-browsers

Recaptcha angularjs verify user's answer

I am using the following plugin https://github.com/VividCortex/angular-recaptcha in order to use recaptcha at a login form.
I am using the following code for verification
$http({
url: 'https://www.google.com/recaptcha/api/verify',
method: 'POST',
params: {privatekey: "key", remoteip: "userip", challenge: "challenge", response: "user_answer" },
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data) {
console.log(data);
if (valid) {
console.log('Success');
alert('Success');
} else {
console.log('Failed validation');
alert('Fail');
// In case of a failed validation you need to reload the captcha because each challenge can be checked just once
//vcRecaptchaService.reload();
}
});
But google server is not returning anything.
I updated the code but no luck.
I think you have a typo in your code:
post: 'GET'
Change that to method: 'GET' or method: 'POST'.
You can check out angular documentation on http to make sure you've written all the params right.
If this wasn't the source of your problems, you should post more details about your issue (what do you see in your networkl console for example).
Keep in mind that recaptcha validation must be done at server-side. I'm not 100% sure that you are doing that in the browser, but your code looks like it.
As Miguel Trias stated, you shall not validate directly from angularjs/javascript client, instead you should send the challenge and response field to your server and validate then.
Therefore you can use the uri you used (https://www.google.com/recaptcha/api/verify) or a plugin, e.g. if you use php see https://developers.google.com/recaptcha/docs/php. I'd prefer a plugin because it will save work.
Furthermore keep in mind that your private key should not be used in the client, this is why it is called private. It is only used to communicate between your server and the reCaptcha servers. The public key is used to communicate between your client and the reCaptcha servers.
For more info read the Overview

Connection between Playframework and ExtJs

I am doing a project were I am trying to make the backend with playframework and the frontend with Extjs.
I can retrieve the data from the server with Json and show it in a grid with all it's fields.
The problem comes when I try to modify, remove or add any record.
The request sent by Ext: DELETE lista?_dc=1318409614652
(I solved _dc with "noCache: false" over the proxy)
The request right now is: DELETE lista
The request I need is: DELETE lista/"parameter of the object like ID or name"
Do you have any idea about this? If you need any information let me know
Thanks in advance!
I suppose you are not yet using the Rest proxy (of ExtJS) for this, but you should, as it does exactly what you are asking for. You set it up with an url like /lista in your case. Now, when you delete a record, the proxy automatically sends a DELETE request to the url, appending it with the id. Check out the documentation (linked above) for more info - you can control the url generation a little bit, but in your case it looks like you can do with the default options.
even if you don't want to use Rest Proxy, you use still use Ext.Ajax.request like below.
Ext.Ajax.request({
waitMsg: "Saving... Please wait",
url: "myserverscript.php",
method: "POST",
params: {
action: "delete",
id: myForm.down('#id').getValue(),
data: jsonData
}
});

Resources