Summernote executes escaped html - html

I fetch data from a MySQL database, the data stored is this:
<p><script>alert('123');</script><br /></p>
When I fetch the data normally I get this as result:
<script>alert('123');</script>
This is fine and works as expected, however when I fetch the data into a textarea which is initialized with Summernote I get an alert like this:
Somehow Summernote converts the escaped html tags to functioning HTML.
How do I fix this?
I have already tried the answer of this question:
Escaped HTML in summernote
It did not work.

Why are you not sanitising data both at the time of storage, and when displayed in the Editor, or outside of the editor? Typically, in my CMS, I don't allow <script/> tags as way to help mitigate users adding potentially dangerous scripts.
That said, there is a PR that is being discussed about how we can best go about fixing this issue. https://github.com/summernote/summernote/pull/3782 information or help would be greatly appreciated to move it along, or even another PR fixing the issue.

I managed to fix it by instead of fetching the data in the textarea fetching it in via jQuery like this:
<textarea name="description" id="description"></textarea>
<script>
$('#description').summernote({
height: 250,
codeviewFilter: false,
codeviewIframeFilter: true,
// toolbar
toolbar: [
['font', ['bold', 'italic', 'underline', 'clear']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['view', ['fullscreen', 'codeview', 'help']]
],
}).on("summernote.enter", function(we, e) {
$(this).summernote('pasteHTML', '<br />&VeryThinSpace;');
e.preventDefault();
});
$("#description").summernote("code", "<?php echo $video->getDetails('', $fileName, 'desc'); ?>");
</script>
Now it doesn't convert > and $lt; to <> if it is the script tag.
See more information here:
https://github.com/summernote/summernote/pull/3782#issuecomment-774432392

Using javascript you can easily fix this. It worked for me in a React + Django project. I also used django_summer_note and it was also showing data like yours. Then I got that solution:
//simply just create a function like this which will return your data (which one you used with django_summernote).
const createBlog = () => {
return { __html: blog.description };
};
// now in your HTML(JSX) show your data like this.
<div className='' dangerouslySetInnerHTML={createBlog()} />

Related

Flask with Summernote And Adding An image - Grabbing The Proper Data?

So im trying to get the information thats being grabbed via summernote textarea. When im not adding an image, everything works perfectly fine and I see the html content from the text editor.
But when I upload a picture, it suddenly gets stuck in a loop??? There more functionality that actually adds the info into the DB, and the image with that ridiculous img src, is saved, but for some reason its iterating the img src over and over? Since then Ive had everything commented out, only to print the textfield content, and for some reason, still get hit with an endless loop the moment I click the submit button? Any help is appreciated, thanks.
flask.py
#app.route("/update", methods=["POST"])
def update():
# Grab Text editor content from form:
contentInfo = request.form["content"]
print("TEST HERE", contentInfo)
html:
<form action="/update" method="POST">
<h1 style="text-align:center">content</h1><textarea name=content id="summernote">{{value}</textarea>
<input class="input-btn" type="submit" value="Update">
</form>
Script init inline within html:
<script>
$(document).ready(function() {
$('#summernote').summernote({
height: 300,
minHeight: null,
maxHeight: null,
focus: true,
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0],editor,welEditable);
}
});
});
</script>
So the text editor and everything works perfect, but the moment I add an image and click submit, my terminal gets stuck in an endless loop, literally need to trash the terminal in order to get it to stop before it crashes.
Any advice is appreciated, thanks.
Results: Over and Over...
Well Stack over flow wouldnt let me post an example, but it was just a bunch of what looked like the img src code from summernote over and over
Update: - So I changed a few things and at least got it to stop looping. I guess it was never looping what it was doing is literally printing out the content of whats being grabbed and apparently its a bunch of crap. I then instead trying to print it with certain params such as "content["img"] only to find out it was slices, so this is apparently an array: But I throw it into type, and it comes back with a class of "bytes" and a length of 529288.... lol! SO the printing wasnt a loop, it was literally printing the 500k lines of this stupid conversion... (super dumb that summernote compiles their images this way in my opinion)
Anyways, Wanted to post the current changes, I feel I am starting to get some progress as it is no longer stuck trying to print out 500k lines. Obviously the data thats being grabbed is the overall app converted into byes? becuase I feel the image conversion is around 7k characters, not 500k...
I feel my issue may be how im trying to grab the data? Since my app is flask and python, it has been a trial an error process trying to get it to work together with the inline javascript. So how my logic works here, is the moment a image is dropped into summernote, it gets thrown into the python logic "updateTest" All im trying to do here, is just grab the image data, so that I can manipulate and do as I wish with the results. How to go about properly grabbing this info? Any advice or insight is appreciated, thanks.
Updated Code:
html:
<form action="/updateTest" method="POST">
<h1 style="text-align:center">content</h1><textarea name=content id="summernote">{{value}</textarea>
<input class="input-btn" type="submit" value="Update">
flask.py:
#app.route("/updateTest", methods=["POST"])
def updateTest():
content = request.get_data()
print("test here", type(content))
print("test here2", len(content))
inline javascript within HTML:
$(document).ready(function() {
$('#summernote').summernote({
height: 300,
focus: true,
callbacks: {
onImageUpload(files) {
sendFile(files[0], data => {
let imgNode = document.createElement("img");
imgNode.setAttribute('src', data.url)
$(this).summernote('insertNode', imgNode);
})
}
}
});
});
var sendFile = function(file, callback) {
var data;
data = new FormData();
data.append("file", file);
return $.ajax({
url: "/updateTest",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data) {
return callback(data);
}
});
};
Any help on how to properly pull this file/image data is really what im looking for right now. Any help is appreciated, thanks
So I finally figured it out. Here is the proper code. now I originally wanted this to work with S3 buckets so in the end, going to that route right off the bat, rather than dealing with the crappy conversion summernote tries to do, I recommend everyone else doing the same thing when coming to something like this:
html:
<form action="/updateTest" method="POST">
<h1 style="text-align:center">content</h1><textarea name=content id="summernote">{{value}</textarea>
<input class="input-btn" type="submit" value="Update">
inline javascript within html:
<style>
$(document).ready(function() {
$('#summernote').summernote({
height: 300,
focus: true,
callbacks: {
onImageUpload(files) {
sendFile(files[0], data => {
let imgNode = document.createElement("img");
imgNode.setAttribute('src', data.url)
$(this).summernote('insertNode', imgNode);
})
}
}
});
});
var sendFile = function(file, callback) {
var data;
data = new FormData();
data.append("file", file);
return $.ajax({
url: "/addImgSummer",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data) {
return callback(data);
}
});
};
</style>
flask.py:
#app.route("/addImgSummer", methods=["POST"])
def addImgSummer():
#Grabbing file:
img = request.files["file"] #<------ THIS LINE RIGHT HERE! Is #literally all I needed lol.
# Below is me replacing the img "src" with my S3 bucket link attached, with the said filename that was added.
imgURL = "https://"+ S3_BUCKET_NAME +".s3.amazonaws.com/images/"+ img.filename
return jsonify(url = imgURL)
NOTE I have logic elsewhere that adds the data to the S3 bucket, the code above simply renders the result from my bucket. I plan on uploading my code to stack overflow on how to do a full s3 bucket situation with summernote. As this right here was just to finish the conclusion of my initial "Being stuck"
Anyways, hope this helps anyone who gets stuck where I did, as there is literally no proper documentation on how to utilize summernote with flask...(Dont get me wrong theres a lot, but none that work..) And even more so, NONE that utilize a better method than converting your image into a 7k byte character sequence, as I see most people doing... Just saving that horrid crap in their DB... So nothing properly working, at least not that I've found the past 3 days of searching..This right here, is the only working solution Ive come across.
The main confusion lies with mixing the javascript in the front end, and talking with your flask/python backend. Once you now how to grab that data, its smooth sailing.

Json query - could not get results from array

I just making small code for tracking app to my website.
I'm pretty new at json so I could not find out what is wrong at my code. It's been two days now:
Here is the code
<http://code.jquery.com/jquery-latest.min.js>
<script type="text/javascript">
$(document).ready(function() {
var inputField = $('#tracking');
var outputElement = $('#textResult');
inputField.keyup(function() {
if (inputField.val().length > 1) {
$.getJSON('http://sporing.bring.no/sporing.json?q=' + inputField.val(),
function(data){
outputElement.html('ID' + data.consignmentSet.consignmentId);
});
} else {
outputElement.html('No result!');
}
});
});
</script>
<div>
<input type="text" id="tracking" style="width: 17;" maxlength="30"/><br/><span id="textResult"></span>
</div>
</body></html>
My source is: http://developer.bring.com/api/trackingapi.html#json
Tracking json source: http://sporing.bring.no/sporing.json?q=TESTPACKAGE-AT-PICKUPPOINT
Links gives result, but i'n not able to display it.
It is simple code, so hopefully someone can explain me what I'm doing wrong...
Thanks
data.consignmentSet contains an array with one element so
data.consignmentSet[0].consignmentId
should work!
You can use JSONLint to validate and pretty print your JSON to better dig into it's structure.
Also, you could use a debugger to explore the content of the data at runtime. Most browsers have their F12 developer tools or you could install Firebug. Then switch to the Script tab, go to the line in code where you access the data and click on the line number. A breakpoint will be set where code execution will stop when running the script. When the breakpoint is reached, you can explore the data in the Watch window.

Word having single quotes search from xml file using jquery issue

Hi I need to parse XML file using jquery. I created read and display functionality. But when a word having single quote not working.
My XML is like this
<container>
<data name="Google" definition="A search engine"/>
<data name=" Mozilla's " definition="A web browser"/>
</ container>
using my jquery code I can read definition of Google. But I can't read Mozilla's definition due to that single quotes. This is my jquery code.
var displayDefinition = function(obj){
$.get("definitions.xml", function(data){
xml_data1.find("data[name^='"+obj.innerHTML+"']").each(function(k, v){
right=''+ $(this).attr("Defination") + '';
}
}
$(".result").append(right);
}
Any body knows the solution for this please help me.
Thanks
jQuery deals with single quotes very well. the structure of your function looks really wild though. I changed it a big assuming you want to create a function that can display the definition based on passing it a name: http://jsfiddle.net/rkw79/VQxZ2/
function display(id) {
$('container').find('data[name="' +id.trim()+ '"]').each(function() {
var right = $(this).attr("definition");
$(".result").html(right);
});
}
Note, you have to make sure your 'name' attribute does not begin or end with spaces; and just trim the string that the user passes in.

How to add spacing in the html() function in jquery?

Hello Guys!
See I have been creating a code powered with ajax but it is way too long and that's why I can't show it here, Sorry for this. But I have created a sample like thing in my Problem Demo link (below). You visit that page and see the problem by your own eyes! But here is the jQuery code of my sample ---
$(document).ready(function () {
$(document.body).html('
<div>
This is Complex Jquery Code Sample!
</div>
');
});
But when I enter my code in a single line (which I'm currently using in my original code) it shows everything perfect. But the problem is in my original code the HTML string is very long and so I'm unable to manage it quickly and effectively! Below is the link for the working one.
WORKING ONE
Hope you guys can help me out with this one. Or else I have to do a long coding on a single line which is very uncomfortable!
PROBLEM DEMO
THANKS IN ADVANCE
If you change your code to look like the following it should work.
Note the double quotes and the \ at the end of each line
$(document).ready(function () {
$(document.body).html("\
<div>\
This is Complex Jquery Code Sample!\
</div>\
");
});
I think you are asking for multi-line strings?
$(document).ready(function () {
$(document.body).html('\
<div>\
This is Complex Jquery Code Sample!\
</div>\
');
});
Do the following:
$(document).ready(function () {
$(document.body).html(''+
'<div>'+
'This is Complex Jquery Code Sample!'+
'</div>'+
'');
});
you can start writing your HTML using a DOM plugin it will be something like this
$(document.body).html($.DIV({}, "This is Complex jQuery Code Sample"));
a table would be something like this:
var table =
$.TABLE({ Class:"MyTable" },
$.TBODY({},
$.TR({ Class:"MyTableRow" },
$.TD({ Class:"MyTableCol1" }, 'howdy' ),
$.TD({ Class:"MyTableCol2" },
'Link: ',
$.A({ Class:"MyLink", href:"http://www.example.com" },
'example.com'
)
)
)
)
);
http://mg.to/2006/02/27/easy-dom-creation-for-jquery-and-prototype
This looks like an excellent use case for jQuery templates.
http://stephenwalther.com/blog/archive/2010/03/16/microsoft-jquery-and-templating.aspx
Is that an option. It would be much easier to maintain a jquery template than it would be to edit large amounts of markup in js syntax.
I don't recommend you to hard-code long strings of HTML code into your JavaScript code. Instead, keep the HTML code inside a .html file, and then retrieve it via Ajax:
code.html:
<div>
This is Complex Jquery Code Sample!
</div>
JavaScript:
$.get('code.html', function(data) {
$('body').html(data);
});

Sending values through links

Here is the situation: I have 2 pages.
What I want is to have a number of text links(<a href="">) on page 1 all directing to page 2, but I want each link to send a different value.
On page 2 I want to show that value like this:
Hello you clicked {value}
Another point to take into account is that I can't use any php in this situation, just html.
Can you use any scripting? Something like Javascript. If you can, then pass the values along in the query string (just add a "?ValueName=Value") to the end of your links. Then on the target page retrieve the query string value. The following site shows how to parse it out: Parsing the Query String.
Here's the Javascript code you would need:
var qs = new Querystring();
var v1 = qs.get("ValueName")
From there you should be able to work with the passed value.
Javascript can get it. Say, you're trying to get the querystring value from this url: http://foo.com/default.html?foo=bar
var tabvalue = getQueryVariable("foo");
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++)
{
var pair = vars[i].split("=");
if (pair[0] == variable)
{
return pair[1];
}
}
}
** Not 100% certain if my JS code here is correct, as I didn't test it.
You might be able to accomplish this using HTML Anchors.
http://www.w3schools.com/HTML/html_links.asp
Append your data to the HREF tag of your links ad use javascript on second page to parse the URL and display wathever you want
http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript
It's not clean, but it should work.
Use document.location.search and split()
http://www.example.com/example.html?argument=value
var queryString = document.location.search();
var parts = queryString.split('=');
document.write(parts[0]); // The argument name
document.write(parts[1]); // The value
Hope it helps
Well this is pretty basic with javascript, but if you want more of this and more advanced stuff you should really look into php for instance. Using php it's easy to get variables from one page to another, here's an example:
the url:
localhost/index.php?myvar=Hello World
You can then access myvar in index.php using this bit of code:
$myvar =$_GET['myvar'];
Ok thanks for all your replies, i'll take a look if i can find a way to use the scripts.
It's really annoying since i have to work around a CMS, because in the CMS, all pages are created with a Wysiwyg editor which tend to filter out unrecognized tags/scripts.
Edit: Ok it seems that the damn wysiwyg editor only recognizes html tags... (as expected)
Using php
<?
$passthis = "See you on the other side";
echo '<form action="whereyouwantittogo.php" target="_blank" method="post">'.
'<input type="text" name="passthis1" value="'.
$passthis .' " /> '.
'<button type="Submit" value="Submit" >Submit</button>'.
'</form>';
?>
The script for the page you would like to pass the info to:
<?
$thispassed = $_POST['passthis1'];
echo '<textarea>'. $thispassed .'</textarea>';
echo $thispassed;
?>
Use this two codes on seperate pages with the latter at whereyouwantittogo.php and you should be in business.