Is it possible to print out the value of a field without being rendered?
In other words, if I have an html like this:
<input value="'" />
And I do:
console.log( $('input').first().val() );
The result will be:
'
While, what I would like is the result to be:
'
is it possible?
Please note this is for debugging proposes only.
The HTML entity is converted to the real character when the HTML is parsed and the DOM is created.
Your JavaScript runs much, much, later than that.
To get the original HTML you would need to make a new HTTP request to fetch the source code of the HTML document, and then write a custom parser (which didn't handle entities) to find the part of the HTML that interested you.
Related
I apologize, this should be simple. I just have a string containing html that I want to append to el as "real html" and return for display.
My code, taken from other stackoverflow answers:
let fragmentFromString = function (strHTML) {
return document.createRange().createContextualFragment(strHTML);
}
let x = fragmentFromString(decodeURI("<span><B>Test</B> this</span>"));
el.appendChild(x);
BUT, all it does is append the text including the html as a child on el. It doesn't actually create the nodes and make "Test" bold, etc...
What I see in my browser is all of:
<span><B>Test<>/B> this</span>
What I WANT to see in my browser is all of:
Test this
What simple thing am I missing? Thank you.
Short answer, you use 'decodeURI' which is wrong in this case, since it's not an encoded URI.
Simply delete it, and it should work.
You should use a html string in your function.
I'm asking this because I'm using a trick that works but I think my be problematic in the future.
I generate a html form in php using SimpleXML and DOM to manage the source (a html file with all forms needed). So I got my form and got to fill some properties. Here is an example:
<input type="hidden" name="arquivo_tipos" value="{arquivo_tipos}" />
{arquivos_tipos} is a JSON string, won't work inside double-quotes. However, if I create the source code like this:
<input type="hidden" name="arquivo_tipos" value='{arquivo_tipos}' />
After being processed by php, it will return to double-quotes (I pick the form from a lot as a xml node). So my solution is replacing the property with this kind of script:
html = html.replace('"{arquivo_tipos}"', '\'[{"ext":"jpg","nome":"Imagem JPEG"},{"ext":"jpeg","nome":"Imagem JPEG"},{"ext":"gif","nome":"Bitmap GIF"},{"ext":"png","nome":"Imagem PNG"}]\'');
This is JavaScript, but in php I use the same trick with str_replace.
The point is, this is the final code, so it works, but smells like it will fails in the future if another process take this result. Is there a better way, a right way of doing this?
Use php htmlspecialchars function, it can escape
double-quotes to "
single-quotes to '
http://tw1.php.net/htmlspecialchars
In a recent review by the AMO editors, my Thunderbird addon's version was rejected because it "creates HTML from strings containing unsanitized data" - which "is a major security risk".
I think I understand why. Now, my problem is about how to solve that issue.
This thread gave me some clues, but it's not quite what I need.
My addon needs to paste the contents of the clipboard as a hyperlink, by using the clipboard contents as the link text, and inserting html around it like this: `" + clipboardtext + "".
Now, if I am inserting the clipboard contents as HTML, I need to "sanitize" it first. Here is what I came up with. Now, I haven't written in the regex part yet, because I don't think this is the best way to do this, although I think it will work:
function makeSafeHTML(whathtml){
var parser = Cc["#mozilla.org/parserutils;1"].getService(Ci.nsIParserUtils);
var sanitizedHTML = parser.sanitize(whathtml, 01);
//now remove the extratags added by the sanitization method, perhaps via regex
//"<html><head></head><body>"
//"</body></html>"
return sanitizedHTML;
}
My intent is to do this with the resulting "sanitized" string - this will paste the string as the href value of a hyperlink:
var html_editor = editor.QueryInterface(Components.interfaces.nsIHTMLEditor);
html_editor.insertHTML("<a href='"+whathref+"'>"+whattext+"</a>");
So I am looking for a better way to get sanitized HTML into a simple string variable. Would any of you do it this way?
It seems that you simply want to insert clipboard contents into HTML code as pure text - you don't need any complicated escaping approach then, it's enough to make sure all "dangerous" characters are replaced by HTML entities:
var sanitizedText = text.replace(/&/g, "&").replace(/</g, "<")
.replace(/>/g, ">").replace(/"/g, """);
It's not clear from your question what you do with the generated HTML code. If you add it to a DOM document via something like innerHTML then you can do better - add the HTML code first and manipulate the text in the document then:
document.getElementById("text-container").textContent = text;
Using Node.textContent to set text in a document is always safe, no escaping needs to be performed.
I am building a pyramid/python app where my view callable for a certain template passes in a value called data. This variable is an array in the form of [[[x1,y1,z1,],...],[[v1,v2,v3],...]]
in my viewcallable I have
import json
jsdata = json.dumps(data)
I want to put it into a javascript script tag section of my template so:
<script>
data=${jsdata}
</script>
but i'm pretty sure that syntax is incorrect. How can I do this?
Edit: from this: http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/templates.html it seems that Genshi style replacements are the way to go, which I take to mean that what I have above is correct. I am still unsure however, about whether this should be treated differently because it is going inside a javascript tag. Is this true?
You want to insert a JavaScript array, not a Python list.
The easiest way to convert between Python and JavaScript formats is to use the json module. JSON is a JavaScript subset for data after all:
import json
jsdata = (json.dumps(data)
.replace(u'<', u'\\u003c')
.replace(u'>', u'\\u003e')
.replace(u'&', u'\\u0026')
.replace(u"'", u'\\u0027'))
then pass jsdata to your template instead. The str.replace() calls ensure that the data remains HTML safe.
In the template, interpolate this without escaping:
<script>
var data = ${structure:jsdata};
</script>
I'm not sure about Chameleon, but "classical" Zope Page Templates did not allow to do anything inside script tags - if you don't see your variables interpolated it is likely that Chameleon behaves the same. The reason for this, as I understand, is to avoid exactly this type of code generation (you're generating JavaScript from Python via the template). Also, ZPT is an XML-based templating language and the content of <script> tags does not have to be a valid XML.
To work around the problem, you could do something like
jsdata = '<script type="text/javascript">var data = ' + json.dumps(data) + ';</script>'
and in your template insert the whole thing:
<tal:myscript replace="structure jsdata" />
Alternatively, you could do something like
<tal:lt replace="string:<" />script>
var data = <tal:script replace="structure jsdata" />;
<tal:lt replace="string:<" />/script>
which would hide the script tags from Chameleon.
It would be a good practice to try to keep the amount of generated JavaScript in your pages as minimal as possible.
There are no inline scripts involved, whatsoever. I have an external file script, which fetches some JSONP from twitter. Let's suppose that a property of the object represented in the returned JSONP was a string that contained somewhere in it the substring "</script>". Could this cause any problems on its own, without getting added to the DOM at all? (It gets scrubbed clean well before that point.)
I can't see why it would, but HTML parsing is notoriously whacky and quirky, so who knows? I know that if you want to have a string literal within an inline script, you need to break it up, like var slashScriptContainingString = 'foo</scr' + 'ipt>bar'; Again, I feel like it should be fine, but just checking to see if anyone knows why it might not be.
<!doctype html>
<script src="file.js"></script>
File.js:
var f = function(twobj) {
console.log(twobj);
doOtherStuffWith(twobj);
}
<script src="https://api.twitter.com/statuses/user_timeline/user.json?callback=f"></script>
Returned JSONP:
f(["this is an object, returned as part of the JSONP response, except it contains a string literal with the substring \"</script>\". Is this a problem? Note: I haven't said anything about injecting this string in the DOM in any way shape or form. I can't think of a reason why it might be, but I'd just like to be sure."]);
No, string literals can contain whatever you want. As long as you are not blindly trying to set the innerHTML of something, a string is just a string. The example you have posted is safe.
The reason that you need to split up your </script> tag in your JavaScript source is that you are missing CDATA blocks. Without them, technically everything in your inline JavaScript needs to be properly escaped for HTML. (< becomes <, etc.) Browsers are nice to you and let it slide, but </script> inside inline JavaScript becomes ambiguous. You should be using CDATA blocks to keep things like this from happening.
<script type="text/javascript">
//<![CDATA[
...code...
//]]>
</script>
See this question for more details: When is a CDATA section necessary within a script tag?