Created
June 29, 2011 17:43
-
-
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
This file contains hidden or 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
<!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> |
This file contains hidden or 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
// 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