Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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);
}
} );
};