Is there a possibility to check the connection to the network in a Firefox extension?
I just want to know if the user is Online or Offline.
I've already tried navigator.online, but it doesn't work.
https://developer.mozilla.org/en-US/docs/Online_and_offline_events is what you're looking for.
And now I'll just ramble to get beyond 30 chars, thanks stackoverflow.
As I'm learned, the Firefox doesn't know if I cut the network connection. So I've created a little XMLHttpRequest (XHR) to set a Boolean:
var netOnline;
function createXMLHttpRequest() {
return Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
}
function issueRequest() {
var req = createXMLHttpRequest();
req.open("GET", "http://google.com", true);
req.timeout = 1000; // ms
// online
req.addEventListener("load", function(event) {
netOnline = true;
});
// timeout -> offline
req.addEventListener("timeout", function(event) {
netOnline = false;
});
// error -> offline
req.addEventListener("error", function(event) {
netOnline = false;
});
req.send();
};
It works fine. Anyhow thanks for your help!
Related
I have some javascript that sends a XMLHttpRequest to a PHP file. This PHP file sends a response, and javascript is supposed to create a URL and redirect to it, using the response text as a parameter. In all other browsers it works fine, but Firefox won't include the response text in the URL.
This is the javascript example:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'filename.php', true);
xhr.onreadystatechange = function(e){
var id = e.currentTarget.responseText;
var urlWithId = "restofurl?id=" + id;
window.location.href = urlWithId;
}
xhr.send(fd);
and filename.php is just a number at the moment:
<?php
echo "3";
?>
I have tried putting other parts of the url (up to the whole url) in the php part, and firefox always cuts out exactly that part. I have also tried copying the response several times to different variable, copying it character by character, putting it in a function that just returns the input again,...
This is only going to be on my own computer, so I don't need to worry about any security issues, so I'm mostly looking for an easy way to cheat around this rather than the way it would be done professionally. Does anyone have any idea?
This is a basic example, you actually have to test readyState status. If i remember well, it is also safer to set the event function before sending the request (not really sure of that).
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
//do something with this.responseText
}
};
xhr.open("POST", url, true);
xhr.send();
EDIT:
This is one of the reasons why i use frameworks, for the old browser support, but this is not an answer. To be more precise, in the past (present?), browsers used to implement exotic functions. It's been a long time i didnt bother to use XHR objects directly, last time it was for file uploads with loading bar (canvas). It shows you the basic way to handle some stuff. This is longer and a bit old fashioned, but well, it works.
function customXHR(){
if(window.XMLHttpRequest){
return new window.XMLHttpRequest;
}else{
try{ //the weird ones
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(ex){
return null;
}
}
}
var xhr = customXHR(), pleaseStop = false, startDraw = false;
if(xhr){
xhr.addEventListener('load', function(e){
var jsonRep;
if(!pleaseStop){
//did use a JSON response
jsonRep = $.parseJSON(e.target.responseText);
//do the rest, we finished
}
}, false);
xhr.addEventListener('error', function(e){
//error
pleaseStop = true;
}, false);
xhr.upload.addEventListener('progress', function(e){
//why not let this as an example!
//file_size must be retreive separately, i fear
if(e.lengthComputable && file_size > 0 && !pleaseStop && startDraw){ draw_progress(e.loaded / file_size); }
}, false);
xhr.addEventListener('loadstart', function(e){
//can be used too
}, false);
xhr.addEventListener('readystatechange', function(e){
if(e.target.status == 404 && !pleaseStop){
//error not found
pleaseStop = true;
}
if(e.target.readyState == 2 && e.target.status == 200){
startDraw = true;
}
/*if(e.target.readyState == 4){
//not used here, actually not exactly the same as 'load'
}*/
}, false);
xhr.open("POST", url, true);
xhr.send();
} //else no XHR support
I am trying to create database and tables in background.js file of Chrome but somehow it's not being created. When I see in Chrome Inspector > Resources > WebSQL, I find nothing. Code is given below:
function fetchData(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/php/fetch.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// JSON.parse does not evaluate the attacker's scripts.
var resp = xhr.responseText;
if(resp != null) {
var json = JSON.parse(resp)
console.log(resp);
var data = json['data'];
if(data != null) {
openDatabase('documents', '1.0', 'my storage', 5*1024*1024, function (db) {
alert('Called'); //This is not being called.
});
//var dbConnection = openDbConnect();
//createTable(dbConnection);
//Code below is called
for(var a=0;a <= data.length;a++) {
alert(data[a].title);
}
}
}
}
}
xhr.send();
}
Update
I guess it's being created: My Extension ID is bkjajbjnoadlhnhmfekipifehbhgidpg
In ~/Library/Application Support/Google/Chrome/Default/databases I find:
chrome-extension_bkjajbjnoadlhnhmfekipifehbhgidpg_0
But it's weird I can't see it in Inspector.
Update #2
Turns out that like pages, WebSQL is not visible across Chrome. It shows Db to the page which is visited. Now I am getting no idea how to excess chrome related Db in Viewer.
To access the inspector for the background page of your app, go to Menu>Settings>Extensions and make sure it's in Developer Mode. It should have a link to inspect the background page of your app in there. It will open up in a new window.
I'm the maker of an addon called BeautifyTumblr which changes the apperance of Tumblr.
I wish for my Chrome extension to automatically detect when it has been updated and display changelog to the user. I use an event page with the chrome.runtime.onInstalled.addListener hook to detect when an update has occured, retrieve the changelog from a text file in the extension.. this all works fine, then when I want to forward it to my content script via chrome.tabs.sendmessage it just wont work, nothing ever happens, no errors no nothing. I'm stumped.
Any help would be much appreciated!
Event Page:
chrome.runtime.onInstalled.addListener(function (details) {
"use strict";
if (details.reason === "install") {
} else if (details.reason === "update") {
var thisVersion = chrome.runtime.getManifest().version, xmlDom, xmlhttp;
xmlDom = null;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", chrome.extension.getURL("changelog.txt"), false);
xmlhttp.send(null);
xmlDom = xmlhttp.responseText;
chrome.tabs.query({'url' : 'http://www.tumblr.com/*'}, function (tabs) {
if (tabs.length > 0) {
var mTab = tabs[0].id;
chrome.tabs.update(mTab, {active: true});
setTimeout(chrome.tabs.sendMessage(mTab, {beautifyTumblrUpdate: xmlDom}), 500);
} else {
chrome.tabs.create({'url' : 'http://www.tumblr.com/dashboard'}, function (tab) {
setTimeout(chrome.tabs.sendMessage(tab.id, {beautifyTumblrUpdate: xmlDom}), 500);
});
}
});
}
});
Relevant code in Content Script:
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
"use strict";
window.alert('test');
if (request.beautifyTumblrUpdate) {
window.alert(request.beautifyTumblrUpdate);
} else if (request.beautifyTumblrInstall) {
window.alert(request.beautifyTumblrInstall);
}
}
);
I am also seeing the same thing. I am not a 100% sure but I think this happens because chrome shuts off connection between background page and "old" content scripts the moment the extension is updated. There's more info here in this bug : https://code.google.com/p/chromium/issues/detail?id=168263
simple, use the following code in background,
chrome.runtime.onInstalled.addListener(function(details){
if(details.reason == "install"){
chrome.tabs.create({ url: chrome.extension.getURL('welcome.html')});
}
});
I want the following function to be called every x seconds, so I don't have to refresh my page.
var rq = new XMLHttpRequest();
rq.open('GET', "SAME DOMAIN ADDRESS", true);
rq.onreadystatechange = function() {
if(rq.readyState === 4) {
if(rq.status === 200) {
clearTimeout(xmlHttpTimeout);
window.location.href = "Tracker.html"; // if internet connection found, redirect.
} else {
}
}
};
rq.send("");
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
rq.abort();
// IF no internet connection found, call this whole javascript function/code AGAIN in 5 seconds! to check for internet connection
}
Basically, I want to check for internet connection without having to refresh my whole page - and if there is, then redirect to Tracker.html
Check if navigator.onLine is true or false.
The best approach is to use setTimeout:
function callMe() {
// Some Code
setTimeout(callMe, 1000);
}
callMe();
Your code will look like that:
var rq = new XMLHttpRequest();
rq.onreadystatechange = function() {
if(rq.readyState === 4) {
if(rq.status === 200) {
window.location.href = "Tracker.html"; // if internet connection found, redirect.
} else {
setTimeout(rq.send, 5000);
}
}
};
rq.send();
If you want to check if the client is connected you can also use the new online and offline events described here.
An ajax solution will only work on the same domain. However on the same domain you will probably not need to test whether the server is online. With navigator.onLine it will indicate whether the internet is accessible however still the appropriate server can be unreachable.
The trick is to try to load an image of the target server and on error then retry after 5 seconds. And when the image has been loaded successfully then a redirect could be done.
<html>
<header>
</header>
<body>
<script type="text/javascript">
var img = new Image();
var ping = function() { img.src = "http://www.somedomain.com/valid_image.jpg"; }
ping();
img.onerror = function(e) {
console.log('error');
setTimeout(function() {
ping();
}, 5000);
}
img.onload = function(e) {
console.log('YES');
window.location.href = "http://www.google.com";
}
</script>
</body>
</html>
I tried all I could think of to at least get to the progress function in IE9 but nothing works. All other browsers get inside of the progress function and write test text without any problems. Hopefully someone can help me. Thank you!
var info = document.getElementById('info');
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
xhr.attachEvent("onprogress", function(e) {
info.innerHTML += "loading...<br />";
});
/*xhr.addEventListener("progress", function(e) {
info.innerHTML += "loading...<br />";
}, false);*/
xhr.open("GET", "10_MB_File.txt", true);
xhr.send(null);
The onprogress event is part of the XMLHttpRequest Level 2 spec...
http://www.w3.org/TR/XMLHttpRequest2/
http://www.w3.org/TR/XMLHttpRequest2/#event-handlers
... which is not supported by IE 9 and below. However, IE 10 is supposed to support it...
http://msdn.microsoft.com/en-us/library/ie/hh673569(v=vs.85).aspx#Enhanced_Event_Support
For more information on which browsers support XHR Level 2, take a look at caniuse.com...
http://caniuse.com/#feat=xhr2
IE9 and under do not support onprogress, hence why you can not get it to work.
var xhr = new XMLHttpRequest();
console.log('onprogress' in xhr);
You could use the onreadystatechange event and display your message. I'm just suggesting it as a workaround.
xhr.onreadystatechange=function() {
if (xhr.readyState != 4) {
// Display a progress message here.
} else if (xhr.readyState==4 && xhr.status==200) {
// Request is finished, do whatever here.
}
}
Adding to suggestion list, if JQuery is used in your project. It can be achieved by below functions and ofcourse, it needs to be JQuery $.ajax request. Advantage of these client libraries is they have objects instantiated based on browsers. For ex: JQuery takes care of "ActiveXObject("Msxml2.XMLHTTP")" or "ActiveXObject("Microsoft.XMLHTTP")" based on browser.
//displays progress bar
$('#info').ajaxStart(function () {
$(this).show();
}).ajaxStop(function () {
$(this).hide();
});