Skip to content

Instantly share code, notes, and snippets.

@maizy
Last active December 14, 2015 04:38
Show Gist options
  • Save maizy/5029231 to your computer and use it in GitHub Desktop.
Save maizy/5029231 to your computer and use it in GitHub Desktop.
CORS test page
<!DOCTYPE html>
<html>
<head>
<title>CORS test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style type="text/css">
body {
font-family: Lucida, sans-serif;
}
form.options,
#results {
padding: 15px;
border: 1px dashed #000;
}
#results {
margin-top: 20px;
}
form.options ul li {
list-style: none;
}
form.options input[type="text"],
form.options select {
width: 400px;
}
</style>
</head>
<body>
<h1>Cross-Origin Resource Sharing (CORS) call for hh.api</h1>
<form id="options" class="options">
<ul>
<li>
<span>Domain</span>
<input name="domain" type="text" value="http://localhost">
</li>
</ul>
<ul>
<li>
<span>Method</span>
<select name="method">
<option selected="selected">GET</option>
<option>POST</option>
<option>HEAD</option>
<option>PUT</option>
<option>DELETE</option></select>
</li>
</ul>
<ul>
<li>
<span>Path</span>
<input name="path" type="text" value="/some_url">
</li>
</ul>
<ul>
<li>
<button type="button">Do!</button>
</li>
</ul>
</form>
<div id="results">
</div>
<script type="text/javascript">
(function () {
var $_results = $('#results');
var debugOutput = function(msg) {
var $div = $('<div/>').text(msg);
$_results.append('<br/>').append($div);
};
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
var stateOfArtSupportBrowser = ( "withCredentials" in xhr );
// XHR for Chrome/Firefox/Opera/Safari.
if (stateOfArtSupportBrowser) {
debugOutput('Use XMLHttpRequest')
xhr.open(method, url, true);
// XDomainRequest for IE.
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
// CORS not supported.
} else {
xhr = null;
}
return xhr;
}
// Make the actual CORS request.
function makeCorsRequest() {
var domain = $('#options input[name="domain"]').val();
var method = $('#options select[name="method"]').val();
var path = $('#options input[name="path"]').val();
var url = domain + path;
debugOutput(method + ' ' + url);
var xhr = createCORSRequest(method, url);
if (!xhr) {
debugOutput('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function () {
var text = xhr.responseText;
debugOutput('Response from CORS request to ' + url+': '+text.substr(0, 40) + '...');
};
xhr.onerror = function (event) {
debugOutput('Woops, there was an error making the request.');
};
xhr.send();
}
$('#options button').click(function(event) {
event.stopPropagation();
makeCorsRequest();
});
window.corsRequest = createCORSRequest;
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment