Skip to content

Instantly share code, notes, and snippets.

@brenttheisen
Forked from benvinegar/subdomain.js
Created May 16, 2011 15:26
Show Gist options
  • Save brenttheisen/974647 to your computer and use it in GitHub Desktop.
Save brenttheisen/974647 to your computer and use it in GitHub Desktop.
Subdomain tunneling with jQuery and document.domain
/**
* Replace $.ajax on your subdomain with a copy taken
* from your base domain. All jQuery AJAX actions go
* through $.ajax (i.e. $.get, $.post), so it's all good.
*/
(function() {
var iframe,
onload,
queue = [],
// This has to be set both here and in iframe.html
document.domain = 'example.com';
// Back up this page's copy of $.ajax
window.$._ajax = window.$.ajax;
// We'll first replace $.ajax with a thin wrapper that both
// loads our iframe tunnel and saves invocations until the
// iframe is ready
$.ajax = function(params) {
if (!iframe) {
// tunnel.html should be a bare bones html page that
// includes a copy of jQuery, and sets document.domain
// to 'example.com'
iframe = $('<iframe>')
.attr('src', 'http://example.com/tunnel.html')
.load(onload)
.appendTo('head')[0];
}
// Save calls to $.ajax, execute when we're ready
queue.push(params);
};
function onload() {
// Our prize: a version of $.ajax that can communicate safely
// with our base domain
window.$.ajax = iframe.contentWindow.jQuery.ajax;
// Flush queued $.ajax calls
$.each(queue, function(_, params) {
$.ajax(params);
});
queue = null;
}
})();
@paulrichards19
Copy link

paulrichards19 commented Aug 31, 2023

I used this solution probably about 12 years ago as i had to support IE6. This now wont work due to all the major browsers slowly making document.domain immutable. https://developer.chrome.com/blog/document-domain-setter-deprecation/ . Working on an alternative.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment