I’ve decided to start contributing a bit more to the world of Free and to open source a few software projects I’ve been working on. This first one, a cross domain ajax library might be interesting to people who have run up against the same-origin restriction for AJAX requests but don’t want to install a proxy (a traditional kludge) or go through the arduous process of getting CORS working on their servers.
This solution uses a feature which was pointed out to me by Emlyn O’Regan which somehow I had not really appreciated until this point. Although JavaScript is really locked down with regard to cross domain scripting, windows pointing to different domains can communicate with one another by posting messages. This can be used to circumvent the restrictions via remotely controlling requests in another window. I like to think of this as “chrome casting” an ajax request via a hidden iframe.
The only requirement for cross domain enabling a remote server is to host a single html file there called xdremote.html. Everything else is handled locally by using my xdloader.js library.
Here is an example of how you could remotely retrieve files from the domain https://jhlagado.github.io/
//create a remote object for the domain
//returns a promise
xdloader.create(‘https://jhlagado.github.io/xdloader/remote/xdremote.html‘)
.then(function(remote) {
//got remote object
//use it to get a file, and parse it as JSON
//returns a promise
remote.get(‘resource1.json’, true)
.then(function(response){
console.log(response.data.message);
})
.catch(function(error){
console.log(‘ERROR: ‘ + error);
})
});
I used a polyfill to enable ES6 promises which are much better than callbacks in most cases. These will become a standard part of JavaScript 6.
The link to github returns a 404 bro. (it goes to the webpage not the repo)
LikeLike
Really? It works for me.
The URL is https://github.com/jhlagado/xdloader
LikeLike
Maybe you need to be logged in?
LikeLike
John Hardy didn’t vote for Abbott I think Andy Ide is referring to this URL https://jhlagado.github.io/ not your post’s URL.
LikeLike
Ah OK. you can see the tests at https://jhlagado.github.io/xdloader/
The resource being loaded is at https://jhlagado.github.io/xdloader/remote/resource1.json
LikeLike
Yeppers – got it – thanks guys!
LikeLike
This is great stuff John Hardy didn’t vote for Abbott , and solves an immediate problem of mine (as you know), so that’s brilliant!
LikeLike
Looking forward to seeing the result! 😁
LikeLike
Ok, I’ve added it to the sUTL editor, here:
http://emlynoregan.github.io/sUTL_js/
Does exactly what it says on the tin!
LikeLike
Awesome!
LikeLike