Run Google Analytics Request in a Chrome Extension Background Script - javascript

Here I have this code, which runs a request to google analytics (I checked, that part works in a popup script) and I would like it to send a daily "order" so to speak to let me know how many daily uses I have installed.
I have set the interval to 5 seconds for testing purposes, but this does not seem to work anyway.
function doSomething() {
chrome.storage.sync.get('session', function(result){
var val = result.session;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://bat.global.cf:8000/checkok.html?rando="+val);
xhttp.send();
xhttp.open("GET", "https://www.google-analytics.com/collect?v=1&tid=UA-232507651-1&cid="+val+"&t=pageview&dp=%2Fdaily24hCheck");
xhttp.send();
});
}
setInterval(doSomething, 5000); // Time in milliseconds
/*Anonymous anylitics code for a background script end*/
Is there something I am missing about background scripts? The request does not seem to be sent, how can I fix this?

You are missing the fact that they are not persistently executing. See the Migrating to Service Workers documentation:
It's common for web developers to perform delayed or periodic operations using the setTimeout or setInterval methods. These APIs can fail in service workers, though, because the scheduler will cancel the timers when the service worker is terminated.
The idiomatic way to achieve what you want here is to use the chrome.alarms API, which is also discussed at that link.
Note that "armed" alarms won't survive a full extension restart (e.g. if the browser is restarted), so you probably should save the last time your alarm code has successfully executed and check if you need to send a beacon / when should you schedule a new alarm on extension start (e.g. through chrome.runtime.onStartup).

Related

Android & Webapp, call background refresh when mobile is locked

For an alert system following a reservation (private use), I would like my webapp to send a notification.
I want every X minutes an ajax call is made, checks if there is a new reservation and if so sends the notification.
I have no problem for the operation and the sending of the notification unless the mobile is locked.
I have seen several posts on this subject but they are dated.
I tried settimetout, setinterval and background-timer, without success.
Maybe today there is a way?
EDIT :
To be more clear. My webapp manages to send notifications even when the mobile is locked, but the verification interval seems random.
A test with a setInterval of 1 minute, sends me a notification after 2 minutes for example, then 5 minutes later... not always with the same interval.
EDIT 2 :
In response to Gowtham K K, I tried using a web worker for the setInterval but it doesn't work when mobile is locked.
Code in my main page :
if(window.Worker){
var myWorker = new Worker("sw2.js");
myWorker.postMessage(0);
myWorker.onmessage = function(e){
var dt = new Date();
var hm = dt.toISOString().substring(11, 19);
_test.innerHTML += hm+"<br>";
}
}
Code in sw2.js
self.onmessage = function(e) {
self.postMessage(0);
init();
}
function init() {
setInterval(send,60000);
}
function send() {
self.postMessage(0);
}
As far as I know, service worker would atleast might solve most of your problem.
Service worker is a background worker for a website. It is supported by most modern browsers.
It acts an proxy layer between browser and web server. For example when user laoded web app and then internet got disconnected. At that time you can register in service worker and so when user connects to internet again, you can make the service worker task to run even when the user is not seeing the webpage.
Here you can handle push notification inside service worker .
Service worker has its own lifecycle.
In your case you can try running the background timer inside the service worker and handle the push notification.
Some Useful links:
https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
https://medium.com/#a7ul/beginners-guide-to-web-push-notifications-using-service-workers-cb3474a17679

Delay an HTML5 notification?

I've been looking at the state of HTML notifications and service workers, and was wondering - is it possible to show a notification on a delay? Basically, I would like to be able to say "remind me in 30 minutes" (or whatever), then push a notification to the user 30 minutes later. That could be scheduled immediately, but I'm not seeing any functionality that allows it.
Am I missing something or is it impossible in the current state of (particularly) Chrome APIs?
This is possible but not straightforward with service workers, at least in their present form. It's not straightforward because a service worker can't keep itself awake for half an hour or wake itself up with a setTimeout or setInterval. The browser will just shut the worker down and will keep no record of any timeouts or intervals. You could wake it up with a message from an open tab, but you said that you don't want to have to have to keep an open tab, and if you assume an open tab then why even bother with the service worker anyway? As Jeff Posnick suggested in a comment, you could perhaps eventually use the Sync or PeriodicSync APIs, but, as he also points out, they aren't implemented yet and aren't really intended for this anyway.
You can accomplish what you want in current versions of Chrome using the Push API, but you'll have to include the server in the loop and set yourself up with a push notification service (i.e. GCM). Here's how it would work, roughly:
When you decide to delay a notification, let the server know about it
After a delay, the server sends out a push message for your user
The service worker is woken up in response to the push and creates a new notification
This last part will be a hassle, because currently you can't actually send any kind of payload with a push, so your service worker will need some way of figuring out what the notification is supposed to be. Maybe the server has a list of snoozed notifications and the service worker can get it from there, or maybe you saved them in IndexedDB.
Adapted from https://developer.cdn.mozilla.net/media/uploads/demos/e/l/elfoxero/c17223c414d8ddafb7808972b5617d9e/html5-notifications_1400214081_demo_package/:
<script>
var Notification = window.Notification || window.mozNotification || window.webkitNotification;
function show() {
window.setTimeout(function () {
var instance = new Notification("Hello World!");
}, 5000);
return false;
}
</script>
Notify me!

SignalR & IE Issue - poll is pending

I have a Problem With IE and SignalR, I'm using the it to perform a Syncing action between two databases, the Actions Completed successfully on Google Chrome / Firefox / Safari in all scenarios.
Using IE for the First time the sync performed successfully but only for one time, in the second time a pending request stack and the page stay freeze for ever.
I found a solution online which is changing the transport mode.
But page still freezing.
if (isIE()) {
$.connection.hub.start({ transport: ['serverSentEvents','foreverFrame']}).done(function () {
progressNotifier.server.DoMyLongAction();
});
}else{
$.connection.hub.start({ transport: ['serverSentEvents','longPolling'] }).done(function () {
progressNotifier.server.DoMyLongAction();
});
}
I'm Using:
SgnalR v2.1.0.0
.Net framework v4.5
jquery v1.8
is it an Issue or I'm Doing something wrong ?
Edit
my application use Jquery progress bar and i Update this progress bar using this Code:
server side:
Clients.Caller.sendMessage(msg, 5, "Accounts");
client side:
progressNotifier.client.sendMessage = function (message, value, Entity) {
pbar1.progressbar("value", nvalue);
};
it's working on Firefox so I thought it's a signalR Issue !! Now i became confused if it's working as expected then what causes this problem ?
you can try use EventSource (SSE).
I am using this:
https://github.com/remy/polyfills/blob/master/EventSource.js
but modified, for SignalR:
http://a7.org/scripts/jquery/eventsource_edited.js
I am working with it for one year, SignalR just check for window.EventSource and it works.
The solution you found online is not likely to help your issue.
I doubt your IsIE() function is correctly identifying IE. If it was, SignalR should only be attempting to establish a "foreverFrame" connection, since IE does not even support "serverSentEvents". I would not expect IE to make any "/signalr/poll" requests, because those requests are only made by the "longPolling" transport.
Also, having a "pending" poll request in the IE F12 tool's network tab is entirely expected. This is how long polling is designed to work. Basically, as soon as a message is received the client makes a new ajax request (a long poll) to retrieve new messages. If no new messages are immediately available, the server will wait (for up to 110 seconds by default in the case of SignalR, not forever) for a new message to be sent to the client before responding to the pending long poll request with the new message.
Can you clarify exactly what issue you are having other than seeing a pending poll request showing up under the network tab? It would also help if you you enabled tracing in the JS client, provided the console output, and showed all the "/signalr/..." requests in the network tab.

Is there any javascript-event which allows an action to be executed by the web-nav continually?

I'm trying to make a websocket using jQuery which is triggered continually after the load of the page. The idea, is to get information continually from the server and to display them into the web page without any refresh.
What kind of event is?
Any brilliant idea, please?
setInterval can be dangerous because of the timing of your http request/response. Better to used chained setTimeouts, e.g.
var tick = function() {
// do something here
$('foo').toggle();
setTimeout(tick, 1000); // wait 1 second and call again
};
tick();
I think an HTML5 Websocket is what you are looking for.
The WebSocket specification defines an API establishing "socket" connections between a web browser and a server. In plain words: There is an persistent connection between the client and the server and both parties can start sending data at any time.
http://html5rocks.com/en/tutorials/websockets/basics

IE hang for 5 minutes when calling synchronous xmlhttprequest

I have a web application and use ajax to call back to my webserver to fetch data.
Sometimes(at rather unpredictable moments, but it can be reproduced) IE hangs completely for 5 minutes(the window says Not Responding) and then comes back and the xmlhttprequest object responds with error 12002.
The way I can reproduce it is as follows.
Open window(B) from main window(A) using button
Window A calls synchronous ajax(PROC1) when button is clicked to open window B. PROC1 Runs file.
New window(B) has ajax code(PROC2) and calls server asynchronous. Runs fine
User closes Window B after PROC2 completed but before data is returned.
In Main Window(a) user clicks button again. PROC1 runs again but now the send() call blocks for 5 minutes.
Please help. I've been looking for 3 days.
Please note:
* I can't test it in firefox (the app is not firefox compatible)
* I have to use synchronous calls (that's the way the app is constructed and it would take too much developer effort to rewrite it)
Why does this happen and how to I fix this?
You're right Jaap, this is related to Internet Explorer's connection limit of 2. For some reason, IE doesn't release connections to AJAX requests performed in closed windows.
I have a very similar situation, only slightly simpler:
User clicks in Window A to open Window B
Window B performs an Ajax call that takes awhile
Before the Ajax call returns, user closes Window B. The connection to this call "leaks".
Repeat 1 more time until both available connections are "leaked"
Browser becomes unresponsive
One technique you can try (mentioned in the article you found) that does seem to work is to abort the XmlHttp request in the unload event of the page.
So something like:
var xhr = null;
function unloadPage() {
if( xhr !== null ) {
xhr.abort();
}
}
Another option is to use synchronous AJAX calls, which will block until the call returns, essentially locking the browser. This may or may not be acceptable given your particular situation.
// the 3rd param is whether the call is asynchronous
xhr.open( 'get', 'url', false );
Finally, as mentioned elsewhere, you can adjust the maximum number of connections IE uses in the registry. Expecting visitors to your site to do this however isn't realistic, and it won't actually solve the problem -- just delay it from happening. As a side-note, IE8 is going to allow 6 concurrent connections.
Thanks for answering Martijn.
It didn't solve my issues. I think what I'm seeing is best described on this website:
http://bytes.com/groups/javascript/643080-ajax-crashes-ie-close-window
In my situation I have an unstable connection or a slow webserver and when the connection is too slow and the browser and the webserver still have a connection then freezes.
By default Internet Explorer only allows two concurrent connections to the same website for download purposes. If you try and fire up more than this, I.E. stalls until one of the previous requests finishes at which point the next request will complete. I believe (although I could be wrong) this was put in place to prevent overloading websites with many concurrent downloads at a time. There is a registry hack to circumvent this lock.
I found these instructions kicking around the internet which alleviated my problems - I can't promise it will work for your situation, but the multi-connection limit you're facing appears related:
Click on the Start button and select Run.
On the Run line type Regedt32.exe and hit Enter. This will launch the Registry Editor
Locate the following key in the registry:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings
Click on the Internet Settings Key.
Now go to the Edit menu, point to NEW
click DWORD Value
Type MaxConnectionsPer1_0Server for the name of this DWORD Value.
Double-click on the MaxConnectionsPer1_0Server key you just created and enter the following information: Value data: 10. Base: Decimal.
When finished press OK.
Repeat steps 4 through 9. This time naming the key MaxConnectionsPerServer and assigning it the same values as indicated in Steps 8.
When finished press OK
Close the Registry Editor.
Of course, I would use these in conjunction with the abort() call previously mentioned. In tandem, they should fix the issue.
IE5 and IE6, indeed, do hang when attempting to receive data from a PHP script. The reason is that these browsers can not decide when has all of the data been received and the connection can be closed. So they wait until connection expires (thus the 5 or 10 minute hang). A way to solve this is to tell to the browser how much data it will receive. In PHP you can do that using output buffering, for example as follows:
ob_start();
echo $html_content;
header( 'Connection: close' );
header( 'Content-Length: '.ob_get_length() );
flush();
ob_end_flush();
This is a solution when one is just loading a normal web page. When one is using
AJAX GET via Microsoft.XMLHTTP object it is enough to
send the "Connection: close" header with the GET request, like
r.request.open( "GET", url, true );
r.request.setRequestHeader( "Connection", "close" );
r.request.send();
Winsock Error 12002 means the following according to msdn
ERROR_INTERNET_TIMEOUT
12002
The request has timed out.
Winsock is the underlying socket transfer object for XMLHTTP in IE so any error thats not in the HTTP error range (300,400,500 etc) is almost always a winsock error.
What wasnt clear from your question is wheter the same resource is being queried the 2nd time round. You could force a new uncached resource by appending:
'?uid=+'Math.random()
To the URL which might solve the issue.
another solution might be to attach a function to the "onbeforeunload" event on the window object to call abort() an any active XMLHTTP request just before the window B is closed.
Hope these 2 pointers solve your bug.
All these posts - Disable PDF reader.. and that stuff... will not resolve your problem...
But sure shot is - RUN WINDOWS UPDATE .. keep uptodate.. This issue gets resolved by itself..
Experience speaks ;)
HydTechie

Categories

Resources