Skip to content

Instantly share code, notes, and snippets.

@aercolino
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aercolino/f84fbda423ccef5fd7c4 to your computer and use it in GitHub Desktop.
Save aercolino/f84fbda423ccef5fd7c4 to your computer and use it in GitHub Desktop.
A jQuery plugin for accessing any URL, using YQL or another proxy.
$.proxyGet = function ( url, callback, options ) {
// reject anything that doesn't resemble a "plain" URL or a null (see below)
if (! (url === null || /^(https?:|\/\/)/.test(url))) {
throw new SyntaxError('Expected a URL.');
}
// allow detection of current SSL mode by starting the url with '//'
if (url && url.indexOf('//') === 0) {
url = window.location.protocol + url;
}
// you are strongly advised to choose a different proxy. YQL "from html" is a toy !!
var yql_proxy = {
// a url with or without a '--URL--' placeholder
// -- the placeholder will be replaced by the url param
// -- use a null url param if the proxy url is requestable as is
url: 'http://query.yahooapis.com/v1/public/yql' + '?q=' + encodeURIComponent('select * from html where url="--URL--" and compat="html5" and xpath="*"') + '&format=xml',
// null (no action) or a function that takes response data and returns clean data
cleanup: function (data) {
data = data.results && data.results[0];
if (! data) return null;
data = data.replace(/
/ig, "\r").replace(/
/ig, "\n");
return data;
},
// null (no action) or a function that takes clean data and returns filtered data
filter: null
};
// use YQL proxy by default, but allow for customizations
options = $.extend(yql_proxy, options || {});
// make the jsonp request
var jsonp_url = options.url.replace('--URL--', encodeURIComponent(url)) + '&callback=?';
$.getJSON( jsonp_url, function (data) {
if ($.isFunction(callback)) {
if ($.isFunction(options.cleanup)) {
data = options.cleanup(data);
if ($.isFunction(options.filter)) {
data = options.filter(data);
}
}
callback(data);
}
} );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment