Skip to content

Instantly share code, notes, and snippets.

@premasagar
Created June 29, 2011 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save premasagar/1054399 to your computer and use it in GitHub Desktop.
Save premasagar/1054399 to your computer and use it in GitHub Desktop.
Wrap random content (e.g. HTML source code) in a JSONP-transportable JavaScript string
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>jsonpx-ify</title>
<script src=jquery.js></script>
<script src=jsonpx.js></script>
<style>
label, textarea, input, button {
display:block;
}
textarea, input, button {
margin-bottom:2em;
}
</style>
</head>
<body>
<h1>jsonpx-ify</h1>
<p>Wrap random content (e.g. HTML source code) in a JSONP-transportable JavaScript string</p>
<label for=source>Put your HTML source code in here</label>
<textarea id=source rows=30 cols=80></textarea>
<label for=callbackName>Callback name</label>
<input id=callbackName value=myCallback>
<label for=stripwhitespace>Strip HTML whitespace</label>
<input id=stripwhitespace type=checkbox checked>
<button id=jsonpxify>Go</button>
<script>
$('#source')
.val('')
.focus(function(){
$(this).select();
});
$('#jsonpxify')
.click(function(){
$('#source').val(
jsonpx($('#source').val(), $('#callbackName').val(), $('#stripwhitespace')[0].checked)
);
});
</script>
</body>
</html>
// E.g. jsonpx(htmlTemplate, 'myFunc');
function jsonpx(html, callbackName, stripwhitespace){
function escape(txt){
var s = '[\\0\\t\\n\\v\\f\\r\\s]';
if (stripwhitespace){
txt = txt
.replace(new RegExp('>' + s + '+<', 'g'), '><')
.replace(new RegExp('(<style[^>]*>)' + s + '+(.)', 'g'), '$1$2')
.replace(new RegExp('(<script[^>]*>)' + s + '+(.)', 'g'), '$1$2');
}
txt = txt
.replace(/'/g, "\\'")
.replace(/(?=\n)/g, '\\');
if (stripwhitespace){
txt = txt
.replace(new RegExp('(;?)' + s + '+<\/script>' + s + '*', 'g'), '$1</script>')
.replace(new RegExp('(;?)' + s + '*<\/script>' + s + '+', 'g'), '$1</script>')
.replace(new RegExp('(}?)' + s + '+<\/style>' + s + '*', 'g'), '$1</style>')
.replace(new RegExp('(}?)' + s + '*<\/style>' + s + '+', 'g'), '$1</style>');
}
return txt;
}
return callbackName + "('" + escape(html) + "');";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment