Created
October 20, 2014 22:31
-
-
Save cmawhorter/46d449c87a37b775a7d4 to your computer and use it in GitHub Desktop.
CORS XHR request of remote HTML with credentials, using jquery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Description: This details how to make a CORS XHR request to a remote HTML resource with credentials, using jquery | |
// Origin website: https://www.origin.example/hello.html | |
// Remote resource: https://www.remote.example/world.html | |
// You can test this locally by configuring your local web server to allow cross origin requests from | |
// google.com. Then you can run the snippet below in devtools from the google homepage. | |
// Remote resource prerequisites: | |
// | |
// 1. Remote resource must respond with an allowed origin. Wildcards are not | |
// allowed. | |
// | |
// During dev, you can do: ResponseHeaders["Access-Control-Allow-Origin"] = RequestHeaders["Origin"] | |
// | |
// 2. Remote resource must respond with ResponseHeaders["Access-Control-Allow-Credentials"] = "true" | |
// Snippet runs on origin. Not sure which min. version of jquery is required. | |
$.ajax({ | |
url: "https://www.remote.com/world.html", | |
type: "get", | |
dataType: "html", | |
xhrFields: { | |
withCredentials: true | |
}, | |
crossDomain: true, | |
success: function (data) { | |
// jquery datatype = html returns a string. we need a documentfragment | |
// this creates one, but will only work on modern browsers supporting the template tag | |
var temp,frag; | |
temp = document.createElement('template'); | |
temp.innerHTML = data; | |
frag = temp.content; | |
// now we can do something with that fragment | |
// this just outputs all the link hrefs | |
Array.prototype.slice.call(frag.querySelectorAll('a')).forEach(function(el) { | |
console.log(el.href); | |
}); | |
}, | |
complete: function() { | |
console.log('complete', arguments); // debugging. not needed, but complete always fires | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment