Javascript html decoding - javascript

When I receive html text by ajax in asp.net application it looks like:
<span%20style='color:green;font-weight:bold'>%20Text%20Msg</span>
how is it possible in javascript decode that text to normal html?
<span style='color:green;font-weight:bold'> Text Msg </span>
Thanks!

Nice function here that does it for you - http://phpjs.org/functions/htmlspecialchars_decode:427

You are probably best suited with finding a server side solution as already mentioned in the comments, since this seems like a server side problem.
If you for some reason wish to do this client side anyway, here is a solution:
var str = "<span%20style='color:green;font-weight:bold'>%20Text%20Msg</span>";
var fixedStr = decodeURIComponent(str).replace(/</g,'<').replace(/>/g,'>');

Related

How to sanitize PHP posted in comments by users

I am creating a commenting system where users can post comments that can also consist of basic HTML including code. Like this:
<pre><code class="language-php"><?php
echo 'Test';
?></code></pre>
The problem is that I can't sanitize this one server side because the PHP code in the comment will actually run on my server. I tried using JavaScript like this before submitting the form:
$("#comment").val() = $("#comment").val().replace("<?", "<?").replace("?>", "?>");
However, this results in Syntax error.
Is there any way for me to safely post user comments that consist of PHP?
to set a new value of input element using jquery, you need to use this syntax
$("#yourElement").val(newValue);
so change your javascript code to:
$("#comment").val($("#comment").val().replace("<?", "<?").replace("?>", "?>"));
read: http://api.jquery.com/val/

built in encode and decode unsafe with databind

I'm trying to implement some client side encoding/decoding onto a databind text box where data is passed between the tb and db.
What I have tried so far is server side functions with visual basic, however when the code is sent through I get an encoding error before the code's had a chance to run so it appears to me that JQuery/JS is the way to go to achieve this.
Can someone explain why it's unsafe to use htmlEncode and Decode like the below and how I need to go about stripping out the html using client side workarounds?
Thanks in advance.
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
function htmlDecode(value) {
return $('<div/>').html(value).text();
}
The biggest problem of this approach is that it does not encode quotes, so if the input is used for an attribute value for example, it may break the html.
elem.innerHTML = '<div title="' + htmlEncode('" onhover="alert(1)') + '">X</div>';
will happily set the element to <div title="" onhover="alert(1)">X</div> and it can run the user's script then.

Working with Javascript BBCode Editor

I know question seems different as there are many BBCodes available out there, I am working on client Side BBCode editor and pretty much had done the work.
The issue i am facing is: when i try to parse the server side data with this:
<cfset show = "<script type='text/javascript'>var data = '#JSStringFormat(answer)#';
document.write(PARSER(data));</script>">
in my view source, it shows like this:
<script type='text/javascript'>var data = '[b]Thanks, This ticket has been Updated[/b]. ';
document.write(PARSER(data));</script>
How can i handle this issue?. I need some good suggestions here
use htmlEditFormat in conjunction with your JSStringFormat function.
var data = '#JSStringFormat(htmlEditFormat(answer))#';
JSStringFormat used alone is prone to XSS attacks.
See Nadal's post
http://www.bennadel.com/blog/2570-For-Better-Security-Use-HtmlEditFormat-In-Conjunction-With-JSStringFormat-In-ColdFusion.htm

Servlet calling from window.showModalDialog(...)

I am calling another application context from window.showModalDialog but confused with following work. Same code to pass parameter within showModalDialg.
var myArguments = new Object();
myArguments.param1 = "Hello World :)";
window.showModalDialog("java2sTarget.html", myArguments, '');
and i can read these myArguments(parameters) in generated HTML using following code:
<script>
document.write(window.dialogArguments.param1);//Hello World :)
</script>
I can't use query string & i am sending myArguments(parameter) because i want to hide parameter from Application user.
Now i am calling servlet from showModalDialog(..)
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
But as per my knowledge
Servlet --> Servlet container --> HTML+JS+CSS
so JS will be available at last phase, but i want to use in first phase(Servlet).
Now, i need to make some Decision in servelt code based on myArguments(parameter).
is there any way to read these myArguments(parameters) in servlet code?
Pass it as a request parameter in the query string.
var queryString = "param1=" + encodeURIComponent("Hello World :)");
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test?' + queryString, myArguments, '');"
No, there's no other alternative. The request URL is not visible in the modal dialog anyway.
As main objective is to hide query string from User to avoid misuse of those parameters.
I tried following work around.
Developers send hidden parameters to get relative information form source(e.g.:DataBase). And we also know that we can send hidden information in Window.showModalDialog using dialogArguments
Work Around:
(i) I got relative information from server one-step before calling Window.showModalDialog using jQuery.getJSON()
(ii) i used google-gson API at servlet side to convert JavaBeans into Json strings.Solution 1 Solution 2
(iii) Convert JSON into javascript object using jQuery.parseJSON
var args = jQuery.parseJSON(json);
window.showModalDialog("pages/"+args.pageName, args, '');
i used args.pageName to make things dynamic
Please suggest improvements in this work-around. Thanks

Using jQuery on a string containing HTML

I'm trying to make a field similar to the facebook share box where you can enter a url and it gives you data about the page, title, pictures, etc. I have set up a server side service to get the html from the page as a string and am trying to just get the page title. I tried this:
function getLinkData(link) {
link = '/Home/GetStringFromURL?url=' + link;
$.ajax({
url: link,
success: function (data) {
$('#result').html($(data).find('title').html());
$('#result').fadeIn('slow');
}
});
}
which doesn't work, however the following does:
$(data).appendTo('#result')
var title = $('#result').find('title').html();
$('#result').html(title);
$('#result').fadeIn('slow');
but I don't want to write all the HTML to the page as in some case it redirects and does all sorts of nasty things. Any ideas?
Thanks
Ben
Try using filter rather than find:
$('#result').html($(data).filter('title').html());
To do this with jQuery, .filter is what you need (as lonesomeday pointed out):
$("#result").text($(data).filter("title").text());
However do not insert the HTML of the foreign document into your page. This will leave your site open to XSS attacks.
As has been pointed out, this depends on the browser's innerHTML implementation, so it does not work consistently.
Even better is to do all the relevant HTML processing on the server. Sending only the relevant information to your JS will make the client code vastly simpler and faster. You can whitelist safe/desired tags/attributes without ever worrying about dangerous ish getting sent to your users. Processing the HTML on the server will not slow down your site. Your language already has excellent HTML parsers, why not use them?.
When you place an entire HTML document into a jQuery object, all but the content of the <body> gets stripped away.
If all you need is the content of the <title>, you could try a simple regex:
var title = /<title>([^<]+)<\/title>/.exec(dat)[ 1 ];
alert(title);
Or using .split():
var title = dat.split( '<title>' )[1].split( '</title>' )[0];
alert(title);
The alternative is to look for the title yourself. Fortunately, unlike most parse your own html questions, finding the title is very easy because it doesn;t allow any nested elements. Look in the string for something like <title>(.*)</title> and you should be set.
(yes yes yes I know never use regex on html, but this is an exceptionally simple case)

Categories