This may seem like a no-brainer, but I can't find a way to do this that isn't considered a security issue (other than the obvious ways)...
So, I want to build an add-on for Firefox to use with my team. Basically it will be a status bar icon letting us know if the authentication cookie for our tools site has expired, so we can tell without losing any work currently in the browser.
At first I thought I could have the add-on check the cookie, but this seems to be a huge hassle for such a simple idea. Then it occurred to me...DUH...that I could just have the add on try to access the main page of our site. If it gets a "Access Denied" response, it can show the icon for "Not Logged In", but if it gets anything else, it can show "Signed In".
However, all attempts to do this with AJAX are proving to be almost as difficult as my cookie attempts.
Is there a simple way, with javascript preferably, but in XUL otherwise, to say
var url = "http://example.com";
var response = pingURL(url, "blah);
status = (response = "Welcome!") ? "Signed in" : "Not Signed In";
where "pingURL" would be the method of "going" to the url and getting the response?
function checkAccess(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
callback(true);
} else {
callback(false);
}
}
};
}
This should work... Just call with "checkAccess('http://example.com', function(ready){});" as an example where ready is a boolean value.
Exactly why do you consider cookies a huge hassle? That would undoubtedly be faster and probably simpler to implement. Reading cookies from chrome is simple and well-documented. Ask for help if you can't figure out how to parse the cookie.
Related
I'm new to web development and am trying to build a small webpage that'll attempt to detect if anyone's currently logged into Instagram on that browser. If I run my code command-by-command in Chrome's console and manually copy-paste the HTML, it works perfectly. But when I try to run my code separately, it seems to run as if it was in Incognito mode.
How would one get around this? If the user needs to grant my page permission to access Instagram, how would I do that?
Here's the JS part of my code:
const USERNAME_REGEX = /"viewer"\:{.*"full_name"\:"([^"]+)"/gm;
const FULLNAME = 'full_name\":\"';
document.addEventListener('DOMContentLoaded', () => {
const request = new XMLHttpRequest();
request.open('GET', 'https://instagram.com');
request.send();
request.onload = () => {
const data = request.responseText;
var u = data.match(USERNAME_REGEX);
if (u != null) {
u = u[0];
u = u.substring(u.indexOf(FULLNAME) + FULLNAME.length).slice(0, -1);
document.querySelector('#info').innerHTML = u;
}
else {
document.querySelector('#info').innerHTML = 'no one is logged in!';
}
}
});
Thank you :) have a wonderful day!
I'm new to web development and am trying to build a small webpage that'll attempt to detect if anyone's currently logged into Instagram on that browser.
That sounds like a security and privacy nightmare, which fortunately for everyone (you included) isn't possible. (Or at least, it shouldn't be...)
If I run my code command-by-command in Chrome's console and manually copy-paste the HTML, it works perfectly.
Totally different context. You'll find, in fact, that if you run this code in a console that isn't on Instagram.com, it won't work.
Same-origin policy will prevent you from accessing another domain. What you're attempting is a classic cross-origin attack that isn't going to work. CORS would get around this, but Instagram surely isn't going to enable you access.
How would one get around this?
You don't.
I have a web project in PHP and it accesses a Java Project that uses the Restlet Framework. The web project is running on Apache and I am testing it using localhost. The Restlet Framework also uses localhost as the domain, but the url is slightly different: localhost:8888/
This is the Javascript that, using Ajax, makes a call to one of the Java classes (CollectionPublic) using the URL above.
var url = "<?php echo $config['restServer_url'] ?>collectionPublic";
var params= "pageList="+facebookPages+"&time="+time;
var client = new XMLHttpRequest();
client.open("POST", url,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.onreadystatechange = function () {
if (client.readyState != 4) return;
if (client.status != 200 && client.status != 304) {
alert("error "+client.status);
} else {
alert("success");
}
callback(client);
}
if (client.readyState == 4) return;
client.send(params);
I have tested and the call is being made correctly, using the URL localhost:8888/collectionPublic, and it is reaching the CollectionPublic class (the class is working fine).
The PROBLEM is: When this call is made, the CollectionPublic class takes a long time to complete its task, and the user should be able to access other pages (on the same server) or reload the page. However, when either of these things happen, the alert("error "+client.status) pops up and the value of client.status is 0. The call is then aborted, but the CollectionPublic's task continue normally, and when it finishes, nothing happens in the web page (before, the alert("success") was being fired).
I spent hours trying to figure out what was causing the error, since this was working last week. Most of the posts I found said that it could be a Cross-Origin Resource problem, since localhost and localhost:8888 are not considered as the same domain. To see if that was really the problem, I started Chrome using the --disable-web-security argument (and it was really disabled) but the issue was still there.
The weirdest thing is that it has worked before, and I changed absolutely NOTHING in the code.
I have seen this post Reloading page while an Ajax request in progress gives empty response and status as zero and it seems quite similar to what I am facing.
Hopefully, I have made myself clear, but if you have any doubts regarding this issue, just ask.
Thanks a lot in advance.
I'm not convinced that the ajax request itself is quite right. if (client.readyState != 4) return; will always be true aside from when its actually 4. This may be better:
client.onreadystatechange = function () {
if(client.readyState < 4) {
//not complete yet
return;
}
if(client.status != 200 && client.status != 304) {
//an error
alert("error "+client.status);
return;
}
if(client.readyState === 4) {
//complete
callback(client);
}
}
As for the problem whereby the ajax call is aborted: This is correct behaviour. All XHR calls will be aborted by the browser as soon the page is reloaded or unloaded. Perhaps this was somehow not the case when viewing pages locally. I would not allow the user to navigate away (or reload) whilst the ajax in progress. As a work-around, your class could set a session variable that is read by your page.
I am working on a simple firefox extension that tracks the url requested and call a web service at the background which detects whether the URL is suspicious or not and based on the result returned by the service, extension decides to stop the page load and alert the user about the case of forgery or whatever, and if user still wishes to go to that page he can get redirected to the original page he has requested for
I have added a http-on-modify-request observer
var observerService = Components.classes["#mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
observerService.addObserver(requestObserverListener.observe, "http-on-modify-request", false);
and the observer
var requestObserverListener = {observe: function (subject, topic, data) {
//alert("Inside observe");
if (topic == "http-on-modify-request") {
subject.QueryInterface(Components.interfaces.nsIHttpChannel);
var url = subject.URI.spec; //url being requested. you might want this for something else
//alert("inside modify request");
var urlbarvalue = document.getElementById("urlbar").value;
urlbarvalue = processUrl(urlbarvalue, url);
//alert("url bar: "+urlbarvalue);
//alert("url: "+url);
document.getElementById("urlbar").style.backgroundColor = "white";
if(urlbarvalue == url && url != "")
{
var browser = getWindowForRequest(subject);
if (browser != null) {
//alert(""+browser.contentDocument.body.innerHTML);
alert("inside browser: "+url);
getXmlHttpRequest(url);
}
}
}
},
}
so when the URL in the URLbar and the requested url matches REST service will be called through ajax getXmlHttpRequest(url); method
now when i am running this extension call is made to the service but before the service return any response the page gets loaded which is not appropriate because user might enter his credentials in the meanwhile and get compromised
I want to first display user a warning message on the browser tab and if he still wanted to visit to that page he can then be redirected to that page on a link click in warning message window
I haven't tried this code out so I'm not sure that suspend and resume will work well but here's what I would try. You're working with an nsIRequest object as your subject so you can call subject.suspend() on it. From there use callbacks to your XHR call to either cancel() or resume() the nsIRequest.
Here's the relevant (untested) snippet of code. My XHR assumes some kind of promise .the() return but hopefully you understand the intention:
if(urlbarvalue == url && url != "")
{
var browser = getWindowForRequest(subject);
if (browser != null) {
// suspend the pending request
subject.suspend();
getXmlHttpRequest(url).then(
function success() { subject.resume(); },
function failure() { subject.cancel(Components.results.NS_BINDING_ABORTED); });
}
}
Just some fair warning that you actually don't want to implement an add-on in this way.
It's going to be extremely slow to do a remote call for every HTTP request. The safe browsing module does a single call to download a database of sites considered 'unsafe', it then can quickly check the database against the HTTP request page such that it doesn't have to make individual calls every time.
Here's some more info on this kind of intercepting worth reading: https://developer.mozilla.org/en-US/docs/XUL/School_tutorial/Intercepting_Page_Loads#HTTP_Observers
Also I'd worry that your XHR request will actually loop because XHR calls creates an http-on-modify-request event so your code might actually check that your XHR request is valid before being able to check the current URL. You probably want a safety check for your URL checking domain.
And here's another stackoverflow similar question to yours that might be useful: How to block HTTP request on a particular tab?
Good luck!
i've been working on some kind of remote control for some time now and figured out a problem that confuses me:
The remote controle is supposed to control some kind of machine. The complete hardware based code is written in c by myself, but thats not really interesting for my problem.
Im using a webserver and a webpage to get access to some basic commands, just like driving forward, backward or turning motor on/off (i use a wlan accesspoint on the board in the machine to connect to it). So far everything works fine, but............:
My Problem is, that there are several options to control the functions of the machine (Terminal, wired-connected Notebook, remote control, "normal" working loop) at the same time. This means, if the machine switches on the motor by itself or a worker uses the terminal, it is neccessary for me to have a feedback on my remote control aswell (at the moment i switch the color of the different button-border from green=inactive to red=active).
The way i did that is easy explained:
If for an example the motor is switched on in c, i write a file with a decimal number that represents a binary code. Just like motor on is 0001 means i write a dec 1. Motor off would be 0010, means i write a dec 2. Because it is possible that there are more than only one function running at the same time i just pass values like 13 (motor on: 0001 = 1; forward: 0100 = 4; lights on: 1000 = 8; => 8+4+1=13). I use a binary AND comparsion to get the actual information about the status afterwards.
Nevertheless i cant refresh the page every two seconds to check the file i write to for changes, im using ajax to have a simple and fancy request possibility:
var http_request = false;
function RequestCommandStatus(url) {
http_request = false;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Ended due to an error!');
return false;
}
http_request.open('GET', url, true);
http_request.onreadystatechange = control4Commands;
http_request.send(null);
}
and after that i do the comparsion stuff:
function control4Commands() {
if (http_request.readyState == 4) {
var answer = http_request.responseText;
if ((answer & 0x1) == 0x1){
//do something
}
if ((answer & 0x2) == 0x2){
//do something
}
if ((answer & 0x4) == 0x4){
//do something
}
if ((answer & 0x8) == 0x8){
//do something
}
}
}
setInterval("RequestValveStatus('myfile.txt')", 1000);
This works pretty good in Firefox but for some reason i got a strange problem in IE8 (even if i enabled every known scripting language and allowed pretty much complete access and control):
For some reason the request seems to be executed once, but after that there is no more interaction between the page and the server. The value of the file changes like it is supposed to. If i reload the page manualy, and for an example, the motor is still running, it changes the color of the border to red. In my opinion this should make sure that the request atleast succeded once.
By using the script debugger of the developer tools, i got the error message, that the http_request.open() failed because of access denied. My first suggestion was that it might be about the path or the type of the file i read from, but i wasnt able to fix it in IE8 with .html, .php, .txt and "several" other types. Also changing the path/origin didnt solved the problem.
I'd really like to discuss this problem with you and feel free to post me your ideas about this way of getting the actual status of the functions.
Greeting,
Ohemgi
I'm sorry for my bad english. Feel free to ask if you cant follow my explanations :-)
try to change
setInterval("RequestValveStatus('myfile.txt')", 1000);
into
setInterval(function() { RequestValveStatus('myfile.txt'); }, 1000);
I'm trying to create my own XMLHttpRequest framework to learn how this things work internally.
A thing that puzzles me is that I cannot find how to catch a "Same origin" exception.
The idea behind this is that I try to load a URL, if I get a Same origin exception, I re-request the URL through a proxy script local for the script. The reason I do this is because I need to access production data from a development sandbox and I want it to be as transparent as possible for the script itself.
I know it's a bad practice but this is the least intrusive way of doing this at the moment :)
Just to clear things - I don't want to bypass same origin, I just want to catch the thrown exception so I can do something about it.
Here is the code I currently use for my xhr:
var net = function (url, cb, setts){
this.url = url;
this.cb = cb;
var oThis = this;
if (!this.xhr) {
this.xhr = new XMLHttpRequest();
this.xhr.onreadystatechange = function() {
if (oThis.xhr.readyState == 4 && oThis.xhr.status == 200) {
document.body.innerHTML += "RS: "+oThis.xhr.readyState+"; ST:"+oThis.xhr.status+"; RP:"+oThis.xhr.responseText+"<br>";
}
else {
// do some other stuff :)
document.body.innerHTML += "RS: "+oThis.xhr.readyState+"; ST:"+oThis.xhr.status+"; RP:"+oThis.xhr.responseText+"<br>";
}
}
}
this.xhr.open("GET", url,true);
this.xhr.send();
} // It's WIP so don't be scared about the unused vars or hardcoded values :)
I've tried to try...catch around xhr.send(); but no avail, still can't catch the exceptions.
Any ideas or pointers would be greatly appreciated.
xhr.onreadystatechange = function() {
if (xhr.readyState==4) {
if (xhr.status==0) {
alert("denied");
} else {
alert("allowed");
}
}
}
Are you sure it's actually supposed to throw an exception? I can't see anything in the specifications: http://www.w3.org/TR/XMLHttpRequest/#exceptions Looks like it does. My bad.
In either case, you can always check the domain of the incoming string against the domain of the page the user is currently on.
FWIW, as you can see by this jsFiddle (open up Web Inspector), Chrome doesn't really throw an exception. It just says "Failed to load resource".