How to send newline commands over Websocket message? - html

Setup
Python FastApi backend server
JS React frontend client
react-use-websocket for frontend ws client
Issue
So I need to send some messages from backend API to frontend client over Websocket connections and display these messages to user. However I don't know how to escape to a new line while displaying these messages. I tried sending \n inside the Websocket message. JS doesn't display this \n character but neither does switch to a newline. It just ignores it. Also tried sending some whitespace but that didn't help either. It just shows a single space regardless of how many whitespaces I left at the API side.
Code
note: TextTransition component is from react-text-transition but the
behavior is same with a standart html paragraph.
const {lastJsonMessage} = useWebSocket(socketURL);
//...
return (
<div>
...
...
<div style={boxStyle}>
<h1 style={{cursor: "default"}}>Message</h1>
<p style={{cursor: "default"}}>━━━━━━━━━━━━━━━━━</p>
<TextTransition
text={lastJsonMessage ? lastJsonMessage.message : ""}
style={{cursor: "default"}}
springConfig={ presets.stiff }
/>
</div>
...
...
</div>
)
What can and should I do? Thanks in advance.

\n does not cause a new line in HTML. You will either need to send <br/> instead, or replace \n on the client side with that, for instance:
<TextTransition
text={lastJsonMessage ? lastJsonMessage.message.replace(/\n/g, '<br/>') : ""}
style={{cursor: "default"}}
springConfig={ presets.stiff }
/>
This assumes that TextTransition accepts HTML (not just text). If the latter then you may be out of luck, because that component just won't let you set control characters in your text.

Related

How to send a new line character "\n" through form tag in html

I wanted to write a POC for XSS through POST method. After playing a lot with html form tags, I was finally able to construct a payload except for a single character "\n". XSS requires that character in order for it to work. Payload looks like this
<input hidden=true type="search" name="
N<html><body><script>alert(document.domain)</script><h1>" value="</h1></body></html>">
However a new line character 
 after being submitted is converted to \n\r instead of \n in HTTP POST request. Is there any work around this problem ??
The solution is strange. Just putting an empty space before 
 solves the problem.

Google MailApp (Javascript) and PRE tag

I am trying to produce an HTML button in a mail message - sending from the Javascript "flavour"of GAS MailApp.
I have tried three different mail readers to eliminate that cause (Thunderbird, Mac Mail and Chrome)
I am sending this HTML via the htmlBody, advanced, parameter of the MailApp:
<script>function blah()
{alert('hi');
}</script>"+
"<input type<pre>=</pre>'submit' id<pre>=</pre>'deleteBookingButton'
value<pre>=</pre>'Delete booking' onclick<pre>=</pre>'this.disabled<pre>=</pre>true;blah()'></br>";
and the message is rendered as:
<script>function blah(){alert('hi=
');}</script><input type<pre>=3D</pre>'submit' id<pre>=3D</pre>'deleteBooki=
ngButton' value<pre>=3D</pre>'Delete booking' onclick<pre>=3D</pre>'this.di=
sabled<pre>=3D</pre>true;blah()'></br>9fgnbterk48818il9j3c933fa0#google.com=
</br>
As you can see the equals signs are not being rendered correctly.
I have tried escaping the equals sign
(&eq; =)
and CDATA.
If at all possible I'd like a raw (ie not Node or similar) solution

Text to HTML conversion in Node Js

I am using nodemailer to send mail from node server. I am getting the content for this mail from MSSQL SQL server which is formatted in plain text format, which meansa there are new line characters in it, however when I send it using nodemailer the newline characters are missing and the whole text looks messed up. The other way is to insert html tags for line break in the plain text and send this works fine. But there is too much mannual work involved what I am looking is for a library or utility which can convert the plain text into the html which I can send using mail.
Is there any liberary for this requirement or a way to do this automatically?
The following will wrap all parts that are separated by more than one newline in paragraphs (<p>...</p>) and insert breaks (<br>) where there is just one newline. A text block without any newlines will simply be wrapped in a paragraph.
template = '<p>' + template.replace(/\n{2,}/g, '</p><p>').replace(/\n/g, '<br>') + '</p>';
So for example, it will take this:
Title
First line.
Second line.
Footer
And convert it to this:
<p>Title</p><p>First line.<br>Second line.</p><p>Footer</p>
The simplest solution is you can replace the new line characters with <br>.
Try
text.split('\n').join('\n<br>\n')
then you are done.
Ok finally this code snippet worked for me -
template = template.replace(/\n/gi, "</p></br/>")
template = template.replace(/<\/p>/gi, "</p><p></br/>")
This was a lot of hit and trial but eventually it worked.

Using ruby variables as html code

I would expect that the following:
<div style="padding-top:90px;"><%= u.one_line %></div>
simply pulls whatever is in u.one_line (which in my case is text from database), and puts it in the html file. The problem I'm having is that sometimes, u.one_line has text with formatted html in it (just line breaks). For example sometimes:
u.one_line is "This is < / b r > awesome"
and I would like the page to process the fact that there's a line break in there... I had to put it with spaces up ^^^ here because the browser would not display it otherwise on stackoverflow. But on my server it's typed correctly, unfortunately instead of the browser processing the line break, it prints out the "< / b r>" part...
I hope you guys understand what I mean :(?
always remember to use raw or html_safe for html output in rails because rails by default auto-escapes html content for protecting against XSS attacks.
for more see
When to use raw() and when to use .html_safe

How to stop an html TEXTAREA from decoding html entities

I have a strange problem:
In the database, I have a literal ampersand lt semicolon:
<div
whenever its printed into a html textarea tag, the source code of the page shows the > as >.
How do I stop this decoding?
You can't stop entities being decoded in a textarea since the content of a textarea is not (unlike a script or style element) intrinsic CDATA, even though error recovery may sometimes give the impression that it is.
The definition of the textarea element is:
<!ELEMENT TEXTAREA - - (#PCDATA) -- multi-line text field -->
i.e. it contains PCDATA which is described as:
Document text (indicated by the SGML construct "#PCDATA"). Text may contain character references. Recall that these begin with & and end with a semicolon (e.g., Hergé's adventures of Tintin contains the character entity reference for the e acute character).
This means that when you type (the invalid HTML of) "start of tag" (<) the browser corrects it to "less than sign" (<) but when you type "start of entity" (&), which is allowed, no error correction takes place.
You need to write what you mean. If you want to include some HTML as data then you must convert any character with special meaning to its respective character reference.
If the data is:
<div
Then the HTML must be:
<textarea>&lt;div</textarea>
You can use the standard functions for converting this (e.g. PHP's htmlspecialchars or Perl's HTML::Entities module).
NB 1: If you were using XHTML[2] (and really using it, it doesn't count if you serve it as text/html) then you could use an explicit CDATA block:
<textarea><![CDATA[<div]]></textarea>
NB 2: Or if browsers implemented HTML 4 correctly
Ok , but the question is . why it decodes them anyway ? assuming i've added & , save the textarea , ti will be saved < , but displayed as < , saving it again will convert it back to < (but it will remain < in the database) , saving again will save it a < in the database , why the textarea decodes it ?
The server sends (to the browser) data encoded as HTML.
The browser sends (to the server) data encoded as application/x-www-form-urlencoded (or multipart/form-data).
Since the browser is not sending the data as HTML, the characters are not represented as HTML entities.
If you take the data received from the client and then put it into an HTML document, then you must encode it as HTML first.
In PHP, this can be done using htmlentities(). Example below.
<?php
$content = "This string contains the TM symbol: ™";
print "<textarea>". htmlentities($content) ."</textarea>";
?>
Without htmlentities(), the textarea would interpret and display the TM symbol (™) instead of "™".
http://php.net/manual/en/function.htmlentities.php
You have to be sure that this is rendered to the browser:
<textarea name="somename">&lt;div</textarea>
Essentially, this means that the & in < has to be html encoded to &. How to do it will depend on the technologies you're using.
UPDATE: Think about it like this. If you want to display <div> inside a textarea, you'll have to encode <> because otherwise, <div> would be a normal HTML element to the browser:
<textarea name="somename"><div></textarea>
Having said this, if you want to display <div> inside a textarea, you'll have to encode & again, because the browser decodes HTML entities when rendering HTML. It has nothing to do with your database.
You can serve your DB-content from a separate page and then place it in the textarea using a Javascript (jQuery) Ajax-call:
request = $.ajax
({
type: "GET",
url: "url-with-the-troubled-content.php",
success: function(data)
{
document.getElementById('id-of-text-area').value = data;
}
});
Explained at
http://www.endtask.net/how-to-prevent-a-textarea-element-from-decoding-html-entities/
I had the same problem and I just made two replacements on the text to show from the database before letting it into the text area:
myString = Replace(myString, "&", "&")
myString = Replace(myString, "<", "<")
Replace n:o 1 to trick the textarea to show the codes.
replace n:o 2: Without this replacement you can not show the word "" inside the textarea (it would end the textarea tag).
(Asp / vbscript code above, translate to a replace method of your language choice)
I found an alternative solution for reading and working with in-browser, simply read the element's text() using jQuery, it returns the characters as display characters and allows me to write from a textarea to a div's innerHTML using the property via html()...
With only JS and HTML...
...to answer the actual question, with a bare-minimal example:
<textarea id=myta></textarea>
<script id=mytext type=text/plain>
™
</script>
<script> myta.value = mytext.innerText; </script>
Explanation:
Script tags do not render html nor entities. By storing text in a script tag, it will remain unadultered-- problem is it will try to execute as JavaScript. So we use an empty textarea and store the text in a script tag (here, the first one).
To prevent that, we change the mime-type to text/plain instead of it's default, which is text/javascript. This will prevent it from running.
Then to populate the textarea, we copy the script tag's content to it (here done in the second script tag).
The only caveats I have found with this are you have to use JavaScript and you cannot include script tags directly in it.