Update client status to server on "onbeforeunload" event - javascript

I have a flash application that needs to send a http request to the server which will disconnect the existing session immediately. I have a tried a few options but none is reliable.
Option #1: On "onbeforeunload" event send a http request from inside the flash applications. Fallacy: This does not work because as soon as the browser is closed the flash player unloads the app and hence the communication breaks.
Option #2: On "onbeforeunload" event send a http request using XMLHTTPRequest in ajax. This works fine in IE but doesnt work in Firefox. When i debugged the http req in httpfox it threw "NS_BINDING_ABORTED" error which i think means that request was cancelled due to page unload.
Note that if i use an alert box, the requests are getting sent in both the options. But i cant use alert boxes. Is there any other way to do so ? or maybe kill the alert box after a timeout ?

It should not be the client's responsibility to tell the server it is disconnecting. You can make the client ping the server regularly to tell it it is still alive, or you could open an never-ending http request (comet-style), and fire the event when the tcp connection is broken.
In PHP it would look somehthing like this: (Not tested)
<?php
// Run script until aborted.
ignore_user_abort(true);
set_time_limit(0);
while(connection_status() == CONNECTION_NORMAL) {
sleep(1);
}
// The connection was lost, so do something.
onLostConnection();
?>

Anyway what was happening was that i was sending a crossdomain xmlhttprequest which is not allowed. see here, http://developer.yahoo.com/javascript/howto-proxy.html . I just fixed the urls and it worked in firefox as well.

Related

How to avoid "fake" AJAX requests in Chrome extension

I am writing a small Chrome extension, and my question mostly about the algorithms. Suppose, my extension should send some AJAX requests to my server. Is there any way to be sure that this particular AJAX request was received exactly from my extension? I mean, make sure that this is not the user sent this request by falsifying it. I will be grateful for any ideas.
You need to check request origin on your server which must contain your extension ID.
When you send AJAX request from your extension the Origin parameter will be like this
chrome-extension://<extension_id>
Now on server you need to check this origin. Example in php
$extensionID = "YOUR_EXTENSION_ID";
$origin = $_SERVER['HTTP_ORIGIN'];
if (strpos($origin, $extensionID) === false) {
// exit from code
exit();
}
Here is complete anwser how to find origin from request.
Now your server will receive AJAX request only from your extension. If someone copy your code and run from another extension, your server will not handle that request.
Note that this will protect you from falsifying requests from other extensions. User still can open your extension background page and send AJAX request from console.

Handle 302 status code upon HTML/JS request to server?

I'm using Require JS and Orace JET
How can we handle the 302 status code or any other status code returned by Server when the session is timeout.
Can it be configured to catch it and redirect the user to a login page upon such cases?
The status code 302 cannot be seen by RequireJS. That's just how browsers work: the browser will see 302 and automatically perform the next HTTP request. RequireJS won't know that there was a redirection.
Any HTTP status code that is an error (500, 400, etc.) will result in a module load failure and onError will be called.
Here is my solution (that works because of luck). Take it just as an inspiration. When session in my app expires, the request is being forwarded using 302 to login page as you would expect. There are 2 main types of requests where it can happen:
REST API call (via XMLHttpRequest)
navigation on page that user did
For #2, the 302 poses no problem. User is simply redirected to login page.
For #1, I can somehow detect it (with some probability) because login page is on different domain that does not support CORS. The XMLHttpRequest request will simply fail with readyState equal to 0 and statusText equal to "error" (because browser will block the XMLHttpRequest to different domain). I have a "listener" (interceptor) on all my REST API calls and whenever some fails with the 0 readyState and "error" statusText, it means that session probably expired.
This is not a solution of course and cannot be used everywhere. Just an idea to think about :)

Chrome extension - how to get response of POST request user invoked from a webpage?

I am trying to create a chrome extension that navigates to a webpage, lets the user click a button on the webpage that sends an asynchronous post request, and to read that response and use it in the extension.
Everything that I am finding from my research is telling me to create the request in the extension itself, which I do not want to do, because I need the web page to make the request itself.
Is there a way to listen to a post request on the page itself on my background script?
You can use chrome.webRequest and onBeforeRequest to fire when a request is about to occur chrome.webRequest.onBeforeRequest.addListener(function callback). Parameters contains the HTTP request data. You also need to supply an extraInfoSpec of requestBody to the listener.
Below is a sample code snippet how to use onBeforeRequest:
const WEB_REQUEST = chrome.webRequest;
WEB_REQUEST.onBeforeRequest.addListener(
function(details) {
if(details.method == "POST")
console.log(JSON.stringify(details));
},
);
For more information regarding POST request, try to read the Chrome Extensions developer guide: https://developer.chrome.com/extensions/getstarted

http post request with cross-origin in javascript

i have a problem with a http post call in firefox. I know that when there are a cross origin, firefox first do a OPTIONS before the POST to know the access-control-allow headers.
With this code i dont have any problem:
Net.requestSpeech.prototype.post = function(url, data) {
if(this.xhr != null) {
this.xhr.open("POST", url);
this.xhr.onreadystatechange = Net.requestSpeech.eventFunction;
this.xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
this.xhr.send(data);
}
}
I test this code with a simple html that invokes this function.
Everything is ok and i have the response of the OPTIONS and POST, and i process the response. But, i'm trying to integrate this code with an existen application with uses jquery (i dont know if this is a problem), when the send(data) executes in this case, the browser (firefox) do the same, first do a OPTION request, but in this case dont receive the response of the server and puts this message in console:
[18:48:13.529] OPTIONS http://localhost:8111/ [undefined 31ms]
Undefined... the undefined is because dont receive the response, but the code is the same, i dont know why in this case the option dont receive the response, someone have an idea?
i debug my server app and the OPTIONS arrive ok to the server, but it seems like the browser dont wait to the response.
edit more later: ok i think that the problem is when i run with a simple html with a SCRIPT tag that invokes the method who do the request run ok, but in this app that dont receive the response, i have a form that do a onsubmit event, i think that the submit event returns very fast and the browser dont have time to get the OPTIONS request.
edit more later later: WTF, i resolve the problem make the POST request to sync:
this.xhr.open("POST", url, false);
The submit reponse very quickly and can't wait to the OPTION response of the browser, any idea to this?
Due to the same origin policy, you can't send cross origin post,
you can workaround it by include sites in iframes (if have access to the domain) original site contains iframe to the outer site, the inner direction is legal.

How to post a file and parse an xml reply in Internet Explorer 7

I have written a web application that posts a file via http to a restful web service. The web service can reply with a 400 or 403 response if the service finds any problems with the request. The response also contains xml describing the reason(s) for replying with a http error code.
My web application posts the file to a hidden iFrame and uses the iFrame's onload event handler to execute a function that parses the server response presented in the iFrame and let's the user know how the file upload went.
My solution works great with firefox and chrome but not in internet explorer 7.
My problem is that if the server responds with an error code e.g. 400 or 403 internet explorer 7 loads its own static error page. This means that my script can't parse the error message sent in the response since the static error page is not from the same domain as the script itself and violates the same origin policy (and since it's a static error page the web service's detailed error message won't be there anyway).
I see only two workarounds to this problem and I would prefer to avoid them both if possible:
A) Have the web service return 200, when the user-agent indicates internet explorer, even though an error has occured but include a xml response that indicates an error.
B) Have the web application post to an "intermediary" that forwards the request to the web service, reads the response and then translates it to a 200 or anything else that works (so it's basically option A but more flexible and at least this keeps the restful web service "clean").
Is there another way to solve my problem?
Assuming you have control of the server, you may find the best solution is to use the iframe only for sending the file (i.e. one way....client to server). Then use an ajax polling solution to determine whether or not the post was successful. It can be a bit messy, but should be much more reliable, and you can also get information back before the post is complete.
I managed to solve this since a colleague remembered that if the response body is not of a certain length when sending a 4xx response, Internet Explorer will load its static error page.
The workaround is to send back a longer response body with your 4xx response, e.g. a xml-comment containing white space.

Categories

Resources