I am using Ajax to check my internet connection after every few second for my application which is using IE instance. But due to low bandwidth my internet explorer is crashing.
What best practise can be followed to check the internet connection so that it prevent crashing of internet explorer and boost performance ?
I am using the following code to check my internet connection.
The explanation of which is given at: -
http://tomriley.net/blog/archives/111 from where I get the jquery file.
(function ($) {
$.fn.checkNet = function (intCheckInterval, strCheckURL) {
if (typeof (intCheckInterval) === 'undefined') {
var intCheckInterval = 5
} if (typeof (strCheckURL) === 'undefined') {
var strCheckURL = window.location
} else if (strCheckURL.indexOf('http') === -1) {
var strCheckURL = 'http://' + strCheckURL
} intCheckInterval = intCheckInterval * 1000; function doRequest(strCheckURL) {
$.ajax({ url: strCheckURL, cache: false, success: function () {
if ($('#netWarn').length) {
$('#netWarn').fadeOut()
} $('.tempDisabled').removeAttr('disabled').removeClass('tempDisabled')
}, error: function () {
if (!$('#netWarn').length) {
$('body').prepend('<p id="netWarn">No internet connection detected, some features will be re-enabled when a connection is detected. </p>'); $('#netWarn').fadeIn()
}
}
})
} setInterval(function () {
doRequest(strCheckURL)
}, intCheckInterval)
}
})(jQuery);
my plugin takes an argument for the length of time between the requests. So, if you want a 10sec interval between requests, call it with this code:
$.fn.checkNet(10);
...after you've included the plugin. I uploaded a new version recently which works much more efficiently.
Related
I have the following code in javascript:
function ConnectWebSocket() {
if ("WebSocket" in window) {
myWebsocket = new WebSocket("wss://myserver/mychannel");
myWebsocket.onmessage = function(evt) {
alert("onmessage");
}
myWebsocket.onopen = function() {
alert("onopen");
myWebsocket.send("msg0");
myWebsocket.send("msg1");
myWebsocket.send("msg2");
}
myWebsocket.onclose = function() {
alert("onclose");
ConnectWebSocket();
}
} else {
// Do something if there is no websockets support
}
}
ConnectWebSocket();
The problem is that in Firefox, the connection is closed after sending the messages, and reopened due to the command on the onclose event. If I try to send only one message on onopen, the connection keeps opened, but if I try to send more than one message, the connection shut down. This issue appears only in Firefox, not in Chrome, not in IE, not in Safari.
Can someone help me? In other browsers like IE or Chrome, once the connection is created, it keep opened until I leave the page. I have the 40.0.3v of Firefox
Try this example:
var url = "ws://echo.websocket.org";
if (!window.WebSocket) alert("WebSocket not supported by this browser");
var myWebSocket = {
connect: function () {
var location = url
this._ws = new WebSocket(location);
this._ws.onopen = this._onopen;
this._ws.onmessage = this._onmessage;
this._ws.onclose = this._onclose;
this._ws.onerror = this._onerror;
},
_onopen: function () {
console.debug("WebSocket Connected");
},
_onmessage: function (message) {
console.debug("Message Recieved: " + message.data);
},
_onclose: function () {
console.debug("WebSocket Closed");
kiosk.connect();
},
_onerror: function (e) {
console.debug("Error occured: " + e);
},
_send: function (message) {
console.debug("Message Send: " + message);
if (this._ws) this._ws.send(message);
}
};
myWebSocket.connect();
setInterval(function() {
myWebSocket._send('msg1');
}, 5000);
Here is a JSFidlle
It may be that your support var is not behaving as you expect. The following code works in FireFox without closing the connection:
function ConnectWebSocket() {
if ("WebSocket" in window) {
myWebsocket = new WebSocket("ws://echo.websocket.org/");
myWebsocket.onmessage = function (evt) {
alert("onmessage");
}
myWebsocket.onopen = function () {
alert("onopen");
myWebsocket.send("a test message");
}
myWebsocket.onclose = function () {
alert("onclose");
ConnectWebSocket();
}
} else {
// Do something if there is no websockets support
}
}
ConnectWebSocket();
Example Fiddle
You can use the tool on Websocket.org to make sure websockets are
working correctly in your browser.
Or (although your issue is with FF) you can use the steps listed
here to debug websockets.
Try it.
var WS = window.WebSocket || window.MozWebSocket;
if (WS){
var websocket = new WS("wss://myserver/mychannel");
}
I am working on a project in which I need to display new data whenever data in database changes, so I am using the local storage concept. Everything is working fine in Chrome and Firefox, but in Internet Explorer it's not working. I understand that it's a problem with local storage in IE. Can anyone suggest a better way of doing this using ASP.net?
if ('localStorage' in window && window['localStorage'] !== null) {
//use localStorage object to store data
try {
var webmethod = top.GetBaseUrl() + '/GetNewlyGeneratedEvents.aspx';
$.ajax({
type: "GET",
url: webmethod,
success: function (msg) {
var htmlCnt = $.parseHTML(msg);
var text = $(htmlCnt).find('#divNewEvents').html();
if (localStorage.length > 0) {
localStorage.clear();
}
localStorage.setItem('NewEvents', text);
UpdateNewEventContent(text);
},
error: function (e) {
alert("error in bringing newEventData");
},
async: true
});
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!');
}
}
} else {
alert('Cannot store user preferences as your browser do not support local storage');
}
I'm a newbie in Ajax and JQuery but I need to invoke a web service in my little web application HTML/Javascript based.
All works fine using Firefox or Chrome but nothing happens using IE (I'm using IE 9 now ...).
Here you are the code
if ($.browser.msie && window.XDomainRequest) {
if (window.XDomainRequest) {
var query = 'http://wms.pcn.minambiente.it/ogc?map=/ms_ogc/wfs/Numeri_Civici_2012.map&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=IN.NUMERICIVICI.2012&SRSNAME=EPSG:4326&bbox=7.70,44.80,7.75,44.85&outputFormat=GML2';
var xdr = new XDomainRequest();
if (xdr) {
xdr.onload = function () {
alert("OK");
}
xdr.onerror = function () {
alert("KO");
}
xdr.open('GET', query);
xdr.send();
}
}
}
else {
var query = 'http://wms.pcn.minambiente.it/ogc?map=/ms_ogc/wfs/Numeri_Civici_2012.map&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=IN.NUMERICIVICI.2012&SRSNAME=EPSG:4326&bbox=7.70,44.80,7.75,44.85&outputFormat=GML2';
$.ajax({
type: "GET",
url: query,
dataType: "text",
crossDomain: true,
success: function (data1) {
alert("OK");
alert(data1)
},
error: function (response, textStatus, errorThrown) {
alert("KO");
alert(errorThrown);
}
});
}
I tried to synthesize in a jsfiddle so you can try if you want.
When I try to execute in IE the browser console tell me that ...
JQMIGRATE: jQuery.browser is deprecated
How can I modify my code?
Thank you all in advance, any suggestion or wokaround will be appreciated!!!
Cesare
The $.browser function is, indeed, deprecated. If you want to detect IE, use this instead:
var browser = navigator.userAgent.toLowerCase(),
isIE = (browser.indexOf("msie")>-1 || browser.indexOf("trident")>-1);
if (isIE && window.XDomainRequest) {
//the rest of your code
}
I'm able to check When there is no internet in my phonegap app using navigator.network.connection.type but when the connection is slow(almost not there) how to check detect such situation using any jquery/javascript code??
You could use setTimeout() to set a maximum time for a request:
var timeout;
var xhr = $.ajax({
type: "GET",
url: "http://myservice.com/jsonp",
data: data,
success: function(msg){
// All went OK
if(timeout != null) clearTimeout(timeout);
}
});
timeout = setTimeout(function() {
// Request took >= 10 seconds
// We could kill it?
xhr.abort();
// Or send a message to the user and ask whether they want to continue
if(!confirm("Network connection is taking longer than usual to complete. Continue waiting?")) {
xhr.abort();
}
}, 10000);
When using Google Chrome extension alarms, the alarm will go off if it was set and Chrome is closed and reopened after the time expires for the alarm.
How can I stop this?
Here is a small code sample to explain what I mean.
/*
If we perform Browser Action to create alarm, then
close the browser, wait about 2 minutes for the alarm to expire
and then reopen the browser, the alarm will go off and the DoSomething
function will get called twice, once by the onStartup event and once
by the onAlarm event.
*/
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.alarms.create('myAlarm', {
delayInMinutes : 2.0
});
});
chrome.alarms.onAlarm.addListener(function (alarm) {
console.log('Fired alarm!');
if (alarm.name == 'myAlarm') {
createListener();
}
});
chrome.runtime.onStartup.addListener(function () {
console.log('Extension started up...');
DoSomething();
});
function DoSomething() {
alert('Function executed!');
}
So if you will read the comment at the top of my code sample you will see what happens.
What I want though, is for the alarm to get cleared if the browser is closed as I want the DoSomething function to get executed only by the onStartup event if the browser is just started, and let the alarm execute the DoSomething function only after the browser is started and my code creates a new alarm.
I never want an alarm to stay around after the browser is closed and then execute onAlarm when the browser is reopened.
How can achieve this?
It's not possible for a Chrome extension to reliably run some code when the browser closes.
Instead of cleaning up on shutdown, just make sure that old alarms are not run on startup. This can be achieved by generating an unique (to the session) identifier.
If you're using event pages, store the identifier in chrome.storage.local (don't forget to set the storage permission in the manifest file). Otherwise, store it in the global scope.
// ID generation:
chrome.runtime.onStartup.addListener(function () {
console.log('Extension started up...');
chrome.storage.local.set({
alarm_suffix: Date.now()
}, function() {
// Initialize your extension, e.g. create browser action handler
// and bind alarm listener
doSomething();
});
});
// Alarm setter:
chrome.storage.local.get('alarm_suffix', function(items) {
chrome.alarms.create('myAlarm' + items.alarm_suffix, {
delayInMinutes : 2.0
});
});
// Bind alarm listener. Note: this must happen *after* the unique ID has been set
chrome.alarms.onAlarm.addListener(function(alarm) {
var parsedName = alarm.name.match(/^([\S\s]*?)(\d+)$/);
if (parsedName) {
alarm.name = parsedName[0];
alarm.suffix = +parsedName[1];
}
if (alarm.name == 'myAlarm') {
chrome.storage.local.get('alarm_suffix', function(data) {
if (data.alarm_suffix === alarm.suffix) {
doSomething();
}
});
}
});
If you're not using event pages, but normal background pages, just store the variable globally (advantage: id reading/writing becomes synchronous, which requires less code):
chrome.runtime.onStartup.addListener(function () {
window.alarm_suffix = Date.now();
});
chrome.alarms.create('myAlarm' + window.alarm_suffix, {
delayInMinutes : 2.0
});
chrome.alarms.onAlarm.addListener(function(alarm) {
var parsedName = alarm.name.match(/^([\S\s]*?)(\d+)$/);
if (parsedName) {
alarm.name = parsedName[0];
alarm.suffix = +parsedName[1];
}
if (alarm.name == 'myAlarm') {
if (alarm.suffix === window.alarm_suffix) {
doSomething();
}
}
});
Or just use the good old setTimeout to achieve the same goal without side effects.
setTimeout(function() {
doSomething();
}, 2*60*1000); // 2 minutes