How does one query for the website's HTTP response code (200, 500, 404, etc) in Chrome's Javascript Console? Since I'm using Chrome in headless mode from command line, I don't have access to the GUI DevTools window. Preferably,
I'd like to know the name of the Javascript API that allows me to query for other HTTP response details from Chrome's Javascript console. I also don't want to install additional extensions to make this work.
Your question is pretty unclear but I'll try my best.
If you need to make requests from the console, you can use the built in javascript APIs fetch or XMLHttpRequest. If you need to check the HTTP status of the current loaded page, you can fetch location.href and log the results. This is technically a different request, but it is the only way to get this information. Here is an example using XMLHttpRequest (for normal code I would recommend fetch but XMLHttpRequest will probably work better in the console):
var req = new XMLHttpRequest();
req.open('get', 'yoururl.com');
req.send();
req.status; //in the console this will automatically log the request status
Depending on where you're opening the console from and what kind of requests you're making, you may run into CORS errors.
If you need to monitor HTTP requests that happen during an application's lifecycle while you are inspecting, you can use chromes monitorEvents utility by entering monitorEvents(XHMLHttpRequests, 'readystatechange') directly into the console. After entering this code, each complete XHMLHttpRequest will be logged to the console. Note that this is only available in the Chrome console and is not present in any other javascript environment.
If neither of these suits your needs then I'm not sure you have any other options.
Related
Using the Azure Storage JS Client library to upload an image throws an error: "Refused to set unsafe header "user-agent""
All requests in the network tab are 200 or 201, it appears like the xhr requests are working. Is it possible to not set this header or filter it out before the post call? I would like to avoid this error in the console.
https://github.com/Azure/azure-storage-node#azure-storage-javascript-client-library-for-browsers
Have tested the sample azurestoragejs-2.9.100-preview in link you mentioned, it causes no error on my side(both Chrome and Firefox).
Open azure-storage.blob.js lib file, search variable var unsafeHeaders and check whether user-agent is in its list. I saw it on my side and reproduce your problem after deleting it. So it might be missing in your file.
If your lib is unbroken, you can ignore this "error" as nothing goes wrong and it's all implemented by storage lib and browser.
Explanation:
When http request executes, method in this lib will make sure headers in unsafeHeaders list won't be set by xhr. If not, browsers will throw warnings as you have seen, because it's a requirement of xhr standard.
See remarks in this lib.
This check is not necessary, but it prevents warnings from browsers about setting unsafe headers.To be honest I'm not entirely sure hiding these warnings is a good thing, but http-browserify did it, so I will too.
Everyting does work on your side may have proved the check is not necessary. Also in xhr standard, user-agent is no more an unsafe header, but browser doesn't catch up.
I want the user to be able to enter their website URL into an input box that is part of a Chrome Extension and the Chrome extension will use an AJAX request or something similar to detect and tell the user if the server behind the URL supports sending responses via HTTP2. Is this possible?
Maybe the WebRequest has a way of picking up this information? Or the new Fetch API? Could your request tell the server somehow that only HTTP2 replies are understood? I can't see an obvious way.
I know you can use window.chrome.loadTimes().connectionInfo to get the protocol of the current page but this requires loading the whole page which I don't want to do.
Example URLS:
Delivered over HTTP2: https://cdn.sstatic.net/
Delivered over HTTP 1.1: https://stackoverflow.com/
HTTP/2 responses require a "status" response header - https://http2.github.io/http2-spec/#HttpResponse, so to check whether the response is using HTTP/2, you can use the chrome.webRequest.onHeadersReceived event with "responseHeaders" in extraInfoSpec. For example, with your test cases:
chrome.webRequest.onHeadersReceived.addListener(function(details) {
var isHttp2 = details.responseHeaders.some(function(header) {
return header.name === 'status';
});
console.log('Request to ' + details.url + ', http2 = ' + isHttp2);
}, {
urls: ['https://cdn.sstatic.net/*', 'http://stackoverflow.com/*'],
types: ['xmlhttprequest']
}, ['responseHeaders']);
// Tests:
fetch('http://stackoverflow.com');
fetch('https://cdn.sstatic.net');
EDIT: Apparently you can do this with the iframe and webRequest trick! I found a reference gist (but I haven't tested it myself though):
https://gist.github.com/dergachev/e216b25d9a144914eae2
OLD ANSWER
You probably won't able able to do this without an external API. Here's why
1) Using ajax only requires that the server of the url to be tested sends CORS headers back to the user, otherwise the browser will not accept it.
2) You could create an iframe on the fly and use chrome.loadTimes().connectionInfo in the iframe contentWindow but if the server sends X-Frame-Options: Deny header the browser won't let you load the url in the iframe either.
3) Stripping the X-frame headers via webRequest API as mentioned here
Getting around X-Frame-Options DENY in a Chrome extension?
will likely not work, afaik Chrome extension are not allowed to modify the response body.
Possible solutions
1) The problems above could be solved using a simple proxy that adds the appropriate headers. Here's a reference on how to do it using Nginx
http://balaji-damodaran.com/programming/2015/07/30/nginx-headers.html
2) Just create a custom API that does the request for you server-side and parses the result to check for http2 support. If your extension gets popular it would still be fairly easy to scale it up e.g via caching and horizontal scaling.
Hope this helps!
Is it possible to read all the HTTP Request/Responses' header and body in a webpage through javascript or through any of its framework?
Screenshot of the required field (opens in the same window)
For example:- Like the way I could view/copy them, through my browser's developer tools.
To my understanding, if I could get hold onto an object or event that fires these requests then I can access the responseText property to fulfill my requirement.
My question is how do I do that? Is it even possible to get all the responseText for all the responses received in my webpage?
(As it has been rendered successfully, then possibly I should be able to access them as well, isn't it?)
I'm just a beginner, so not sure if my question is meaningful. Thanks for all the replies.
If I'm understanding correctly, you're asking how to retrieve detailed network traffic information for a given website. This is browser specific: Chrome for example exposes the chrome.devtools.network object which you can interrogate. See https://developer.chrome.com/extensions/devtools_network
Try this following javascript code:
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
it will get all the HTTP headers.
I am looking for a way to allow browser-hosted JS app to make requests to server running on different port and, possibly, different machine than that which is serving up JS app in the first place.
I am serving a simple JavaScript (HTML5) app from my Mac OS X Apache web server. I would like to be able to run this app in as many browsers as possible across Windows, Android and OS X. But I would settle for one on each.
My JavaScript app uses XMLHttpRequest to make requests of a minimal custom server that returns JSON.
So, for example, my JS app is accessible at http://10.0.1.3/poc/dashboard.html
and my custom server is running on same machine, listening on port 49379 ... a request like this http://10.0.1.3:49379/find?name=Fred would return a set of tuples where 'name' equals 'Fred'.
If I enter this request directly into navigation toolbar, then I get desired result.
If I make same request within JS, I get a couple of errors.
var theXHR = new XMLHttpRequest();
theXHR.onreadystatechange = onReadyStateHandler;
theXHR.open("GET", "http://" + ipAddress + ":49379/find?name=Fred", true);
theXHR.setRequestHeader("User-Agent", "XMLHTTP/1.0");
theXHR.send(null);
I get these two errors:
Refused to set unsafe header "User-Agent"
XMLHttpRequest cannot load http://10.0.1.3:49379/find?name=Fred.
Origin http://10.0.1.3 is not allowed by
Access-Control-Allow-Origin.
I have control over Apache server, JavaScript and custom server. This is just a proof of concept piece that will be demoed on isolated networks. So, I am not concerned with security issues.
Also, I am running in Chrome, Firefox, Safari. All of these appear to use the XMLHttpRequest2 object.
I have found the way to get around CORS is to use jsonp - which is json with a callback function - I've never used it with XMLHttpRequest, but it works with jQuery ajax functions like $.getJSON. In your url query string simply add the parameter jsoncallback=? and voila, no more CORS problems. $.getJSON dynamically assigns its success parameter to the callback function.
I'm using jQuery's .ajax() to call a server (actually local Django runserver) and get a response.
On the server console, I can see that the JSON request comes in, he proper JSON response is made, and everything looks OK.
But in my browser (tested on Firefox 3.6 and Safari 4.0.4, and I'm using jQuery 1.4.2), it seems the response body is empty (the response code is 200, and the headers otherwise look OK).
Testing the response from the command line, I get the answer I expect.
$ curl http://127.0.0.1:8000/api/answers/answer/1 --data "text=test&user_name=testy&user_location=testyville&site=http%3A%2F%2Flocalhost%3A8888%2Fcs%2Fjavascript_answer_form.html&email_address="
{"answer_permalink": "http://127.0.0.1:8000/questions/1", "answer_id": 16, "question_text": "What were the skies like when you were young?", "answer_text": "test", "question_id": "1"}
I am making the request from an HTML file on my local machine that is not being served by a web browser. It's just addressed using file://. The django server is also local, at 127.0.0.1:8000, the default location.
Thanks for any suggestions!
-Jim
Unless you specifically allow your browser alternate settings for local files, everything remains bound by the cross-domain security policy. Files not on a domain (like localhost) can not request files from that domain.
I'm not sure how cross-domain policy works with ports; you may be able to put this file in your port-80-accessible localhost folder (if you have one) and get the job done. Otherwise, you're stuck, unless you can change browser settings to make exceptions (and even then I'm not sure this is doable in any standard browsers).
Add an "error: function(data){alert(data);}" to see if your $.ajax is failing.
Change 'complete' to 'success' in your .ajax() call. 'complete' is used to signal when the ajax operation is done but does not provide the response data. 'success' is called with a successful request and receives the response. 'error' is the counterpart to 'success', used for error handling.
I think browsers (at least some, like Safari, for me) treat files served off the file system as trusted sources in terms of the same-origin policy. So that turned out to be a red herring here.