Last active
August 29, 2015 14:02
-
-
Save aercolino/f84fbda423ccef5fd7c4 to your computer and use it in GitHub Desktop.
A jQuery plugin for accessing any URL, using YQL or another proxy.
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
$.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
See http://andowebsit.es/blog/noteslog.com/post/how-to-workaround-the-same-origin-policy/