Get source code for a specific page using JavaScript - javascript

The code below displays the source code of the current page:
Website as example: http://jsfiddle.net/635YY/1/
var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);
How to display the source code of another page (other than the current page)?

url="/about";
var xhr = new XMLHttpRequest();
xhr.onload = function() {
alert( this.responseXML.documentElement.innerHTML );
}
xhr.open( 'GET', url );
xhr.responseType = 'document';
xhr.send();
Unfortunately you will not be able to do this with pages on another website unless the CORS policy on the website allows it, or you will get an error like
Access to XMLHttpRequest at 'https://test.com/' from origin 'http://jsfiddle.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Related

xmlHttpRequest returns status 0

I can't get xmlHttpRequest to return any status but 0. The responseText is always empty. No matter, which url I am opening, this happens. Could someone tell me what I am doing wrong?
var url = "http://stackoverflow.com/";
var xmlHttp = new XMLHttpRequest();
var response = document.getElementById("response");
xmlHttp.open("GET", url, true); // true for asynchronous
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
response.innerHTML = xmlHttp.status;
};
https://jsfiddle.net/6ub7ct6j/
Thanks in advance
Check the console. You're trying to load an http resource from an https page, and the browser is blocking it. However, if you try https://stackoverflow.com, you'll get a CORS error.
stackoverflow.com doesn't allow access via Ajax:
VM94:1 XMLHttpRequest cannot load https://stackoverflow.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fiddle.jshell.net' is therefore not allowed access.

Chrome Extension blocked from a rails API

I am just trying to talk with a REST api on a Rails site.
I am using a Chrome extension and javascript to make a CORSRequest.
I get this error whenever I try to make a request:
XMLHttpRequest cannot load https://MYWEBSITE.com/api/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://mychomreextensioncode' is therefore not allowed access. The response had HTTP status code 404.
Here is my current code:
function makeCorsRequestLogin() {
var url = "https://MYWEBSITE.com/api/login";
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onload = function() {
var text = xhr.responseText;
var title = text; //getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
if (!xhr) {
alert('CORS not supported');
return;
}
xhr.onerror = function() {
alert('Woops, there\'s an error making the request.');
};
var password = document.getElementById("password").value;
var user_name = document.getElementById("username").value;
xhr.send(JSON.stringify({"user_name":user_name, "password":password}));
}
Elsewhere, in the past, people have said that this code solves it. But, I have no idea where this could would go.
# This is used to allow the cross origin POST requests made by confroom kiosk app.
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = "*"
headers['Access-Control-Request-Method'] = %w{GET POST OPTIONS}.join(",")
end
I am only working in JS and HTML on a chrome extension. I do not have access to the ruby site. Can I solve this problem from only my end?
You should define permission for your server domain in the manifest.json.
"permissions": ["https://MYWEBSITE.com/*"]
Also make sure you set the right protocol whether it's http or https.

Cross-subdomain request

I need to make a cross subdomain request. There is a classic asp site which create an XMLHttpRequest to my PL/SQL Oracle webpage.
The asp site has the domain: test/site.asp and the PL/SQL webpage has the domain test:7779/site... so the top level domain is the same
This is my XmlHttpRequest:
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onload = function() {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
createChart(divID, xmlHttp.responseText, counter);
} else {
console.error("error");
}
}
};
xmlHttp.open( "GET", theUrl);
xmlHttp.setRequestHeader( "pragma", "no-cache" );
xmlHttp.send( null );
No error occurs in IE11, but in Chrome:
XMLHttpRequest cannot load http://test:7779/site
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://test' is therefore not allowed access.
The response had HTTP status code 501.
Is there a solution to make a cross subdomain request? Maybe with an iframe in my asp site, to get the content?
UPDATE:
I know tried to set the document.domain at both sides to the same: test. But this also didn't solved the problem.
My suggestion is, why dont you use MSXML2.ServerXMLHTTP object, as you have Classic ASP in hand? So that XMLHttp request will be sent from server to server and not from browser.
You can use it like this,
Dim xmlhttp
Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.setTimeouts 30,500,1000,1000
xmlhttp.Open "GET", "http://yourlink" & time, false
On Error Resume Next
xmlhttp.Send
If Err.Number Then
getBBstatus = "Could Not Retrieve Data"
Err.Clear
Else
getBBstatus = xmlhttp.ResponseText
' Do something with the response here
End If
On Error Goto 0
Set xmlhttp = nothing
Hope it helps, thanks.

Requesting Google Place API with xhr got CORS issue

On my webpage I have some javascript code to query Google Place API (GET) for response. Here's my code look like:
// Sending XHR request
var url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=KPMG+Seattle&key=<<MY_KEY>>';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.send();
//**********************//
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
}
else {
// CORS not supported.
xhr = null;
}
return xhr;
}
I am running this local HTML file in my browser, and got CORS error:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
I am wondering what the problem can be (I added Access-Control-Allow-Origin to request header)? According to the Google Tutorial this should be enough to make a request?
Please help point out where I am doing wrong... Thanks!
Please see this post XMLHttpRequest Origin null is not allowed
Basically there is a security feature you need to disable to allow XHR of different origin if you are running from a local file.
See the first answer in the post.

How to get some page by url in javascript

I want to get page from web-site using javascript.
I have url like:
http://not-my-site.com/random
From 'random' I will be redirected to another (random) page on the web-site.
Postman do everything like I want :) It's get whole page (html). But how can I do the same from javascript?
I tried CORS alredy following this guide http://www.html5rocks.com/en/tutorials/cors/ but without success. I still just get an error:
XMLHttpRequest cannot load http://not-my-site.com/random.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Code from tutorial:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', 'http://not-my-site.com/random');
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.onload = function() {
var responseText = xhr.responseText;
console.log(responseText);
// process the response.
};
xhr.onerror = function() {
console.log('There was an error!');
};
xhr.send();
And also I tried common xhr like this (got the same error):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://not-my-site.com/random', true);
xhr.send();
This seems to be a problem of CORS not being configured correctly on the server. The below PHP code should allow any request from any domain. (If you're not using PHP, it should be easy to convert the below code into any other language, the clue is to write to the HTTP header).
Remember to place this code before any HTML is outputted.
$origin=isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:$_SERVER['HTTP_HOST'];
header('Access-Control-Allow-Origin: '.$origin);
header('Access-Control-Allow-Methods: POST, OPTIONS, GET, PUT');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, X-Requested-With');
header('P3P: CP="NON DSP LAW CUR ADM DEV TAI PSA PSD HIS OUR DEL IND UNI PUR COM NAV INT DEM CNT STA POL HEA PRE LOC IVD SAM IVA OTC"');
header('Access-Control-Max-Age: 1');
Accepting requests from all domains is insecure. For a better (but slightly more complex) solution, see here: CORS That Works In IE, Firefox, Chrome And Safari

Categories

Resources