I stumbled upon https://codereview.stackexchange.com/questions/10610/refactoring-javascript-into-pure-functions-to-make-code-more-readable-and-mainta and I don't understand the answer since the user uses an # symbol in a way I've never seen before. What does it do when attached to the if keyword? Can you attach it to other keywords?
It's not a JavaScript thing. It's a symbol used by whatever templating system that answer was referring to. Note that the <script> element has type text/html, which will prevent browsers from paying any attention to its contents.
Some other JavaScript code will find that script and fetch its innerHTML in order to merge the template with some data to create ... well whatever that template makes.
#: syntax in Razor
Said by #StriplingWarrior at Using Razor within JavaScript
It is razor code, not javascript, if you are interested in razor check:
http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx
Related
What is the correct way to escape JavaScript in C# / ASP.NET?
For example:
<script>
var abc = '<%= def%>';
</script>
<div onclick="myfunction('<%= Xyz%>')" />
There are surely questions about this, but listing different options. There are
System.Web.HttpUtility.JavaScriptStringEncode
System.Web.Util.HttpEncoder.JavaScriptStringEncode
Microsoft.Security.Application.Encoder.JavaScriptEncode
Microsoft.JScript.GlobalObject.escape
System.Text.Encodings.Web.JavaScriptEncoder (Core)
any other?
Results from these methods are not always the same and their documentation does not seem to clearly describe the use case.
In case of the latter example we probably should employ both HTML and JS encoding, I was able to exploit System.Web.HttpUtility.JavaScriptStringEncode when used without HTML encoding. However Microsoft.Security.Application.Encoder.JavaScriptEncode is so thorough that while I would still add HTML encoding to be proper, I can't see a way how it can be exploited.
JSFiddle: https://jsfiddle.net/1afn5dky/
Does each method have a preferred use case?
The best answer for your specific usecase can be derived from OWASP Cheatsheet Rule #3
In general, this boils down to 1) the correct encoding actions and their order and 2) implementation.
Encoding actions and order here is fairly simple - you need to do javascript encoding. Beware the onclick use case though. If the function you mention is designed to execute code, you will probably need to come up with additional layer of sanitization. More information in this SO thread
As for the implementation, the owasp cheatsheet mentions now obsolete AntiXSS, which has been superseded by AntiXssEncoder class now present in .NET Framework and .NET Core. This can be used by HttpUtility class behind the scenes if you follow this setup in web.config, like so:
<httpRuntime ...
encoderType="System.Web.Security.AntiXss.AntiXssEncoder,System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
Without this setting, HttpUtility class uses HttpEncoder behind the scenes. (In your specific use case, JavaScriptStringEncode method is actually the same for both classes though).
In your first scenario:
<script>
var abc = '<%= def%>';
</script>
If def will evaluate to data rule 3.1 specifically recommends putting them into a separate element, evaluating them as a json string and then using json parser to read the data:
<div id="init_data" style="display: none">
<%= html_encode(def.to_json) %>
</div>
// external js file
var dataElement = document.getElementById('init_data');
// decode and parse the content of the div
var abc = JSON.parse(dataElement.textContent);
If this is however impossible because def evaluates to a javascript function call, this approach is not possible. In this scenario, I think you need to change your design as codegen is usually a bad idea and you could have either do the full codegen on backend side or frontend (using an appropriate frontend framework). If for some strange reason you just cannot do any of these options, than you need to encode nested context (JS in HTML), and on top of that you also need to do sanitization of the resulting javascript calls.
Second example <div onclick="myfunction('<%= Xyz%>')" /> should be used with respect to rule 3, so HttpUtility.JavaScriptStringEncode should suffice. However, if your function executes the parameter, you should also sanitize it.
There's some good reasons to avoid the eval() function in JavaScript, namely security risks when including user input in the eval() code. However, in a situation where the eval() code does not include anything affected by user input (in my particular situation, we have dynamic templates defined in XML files - these templates can also specify complex validation functions, javascript code that is embedded in the XML, which is then received by the client via AJAX), is there any reason to avoid the eval() function?
I came up (I'm probably not the first, but I haven't seen this done) with a solution using a dynamically created inline tag instead of eval():
$(scriptObject).text(strJSCode);
A simple example can be seen at http://jsfiddle.net/H7EG9/1/ (I know this example does use user input, but that's just to make it easy to demonstrate).
Is there any reason to do this instead of eval()? The outcome is basically the same, although this option might appear less "scary" to the die-hard foes of eval().
I would use eval instead of creating script tags.
Script tags create overhead (they are DOM elements) but more importantly, you will need to use some sort of global variable to access the script in the script tags. If you use eval, you can simply do
var evalFunction = eval("(function(){...})"); // wrap function in () to make it an expression
var result = evalFunction(val);
IE8 and below do not allow scripts to be served in data: format. In that regard, eval() is more reliable.
That being said, if you are using AJAX to download a JS file from which you are getting that string, you could just set scriptObject.src = 'path/to/script.js'; The browser will have the file in cache and will therefore load it immediately.
eval is easy to write, but it is nearly as easy to add a script element to the head or body and append the js text to the new script element. Some edge cases, like variable hoisting, behave a little oddly when evaling a script.
Has anyone implemented John Resig's micro-templating in production code? In particular I'd like to know if embedding the templates with <script type="text/html"> has caused any problems.
A bit more information: here's the sort of thing I'm worried about:
My users are mostly in corporate environments - could an unusual proxy server mangle or strip out the templates
The embedded templates seem to fail W3C validation. What if, for instance, the next version of IE decides it doesn't like them?
I abandoned inlining templates through scripttags as my view layer would create redundant duplicate script templates. Instead I placed the templates back into the JavaScript as string:
var tpl = ''.concat(
'<div class="person">',
'<span class="name">${name}</span>',
'<span class="lastname">${lastName}</span>',
'</div>'
);
I used the string concat trick so I could make the template string readable. There are variations to the trick like an array join or simply additive concatenation. In any case, inline script templates works and works well, but in a php/jsp/asp view layer, chances are you will create redundant duplicate script templates unless you do even more work to avoid it.
Furthermore, these templates become rather complex the more logic you have to add to them, so I looked further and found mustache.js which imo. is far superior and keeps the logic (conditions and dynamic variable definitions) in the JavaScript scope.
Another option would be to retreive template strings through ajax, in which case you can put each template inside it's own file and simply grant it a .tpl extention. The only thing you have to worry about is the http request roundtrip, which should not take too long for small .tpl files and is imo. insignificant enough.
While I haven't used #jeresig's micro-templating, I did roll my own which uses <script type="text/html">. I've used it in a couple of (albeit basic) production sites without problems. The HTML5 spec itself refers to something similar (near the end of the section I've linked to). AFAIK the block only executes when the MIME type is a recognized script type, otherwise the block is just part of the document.
I have actually, and it works great. Though only for webkit powered browsers so can't vouch for others. But what problems are you expecting? The approach is simple and I can't think of how it might break.
If you're using jQuery I can recommend jQuery templates instead:
http://github.com/nje/jquery-tmpl
I think it's supposed to be introduced officially in jQuery 1.5
BTW. I think both Resigs script and jQuery templates relies on using innerHTML, so as long as that works in your browser you should be OK.
I don't know if this is possible/sensible, but I was curious to know if I can have my strings in javascript files have html highlighting. I discovered that strings in php could have SQL syntax highlighting, so I believe it is possible.
But, I don't know vim-scripting, so any help on this appreciated.
I am using the Better Javascript syntax.
PS: If there could be an option to turn it on and off while editing a js file, that would be wonderful
Thanks
Yes, it's possible if you don't mind some syntax file hacking. First you need to include the HTML syntax file from within the Javascript syntax file -- see :help syn-include for info on that; second you need to declare that HTML syntax can be found inside of certain elements (i.e. strings). Third, if you want to have the option of enabling and disabling it, you can make those commands dependent on a global variable, and write some mappings that set or unset the variable and then reload the syntax file.
For examples on how inclusion works, take a look at syntax/html.vim (which includes the Javascript and CSS syntax files), syntax/perl.vim (which includes the POD syntax file), or php.vim (which includes SQL syntax highlighting in strings, conditional on a global ariable).
Edit: did some work on actually making this happen in my copy.
In the head of syntax/javascript.vim, just below syn case ignore, add
syn include #javaScriptHTML syntax/html.vim
unlet b:current_syntax
syn spell default " HTML enables spell-checking globally, turn it off
Then add #javaScriptHTML to the contained= lists for javaScriptStringD and javaScriptStringS.
Finally you have to edit syntax/html.vim to prevent it from trying to include syntax/javascript.vim if it was loaded from javascript: find the line that reads
if main_syntax != 'java' || exists("java_javascript")
and change it to
if main_syntax != 'javascript' && ( main_syntax != 'java' || exists("java_javascript")
I'm developing a facebook app right now all by my lonesome. I'm attempting to make a javascript call on an onclick event. In this onclick event, I'm populating some arguments (from the server side in php) based on that item that is being linked. I'm inserting a little bit of JSON and some other stuff with funky characters.
Facebook expects all the attribute fields of an anchor to be strictly alphanumeric. No quotes, exclamation marks, anything other than 0-9a-Z_. So it barfs on the arguments I want to pass to my javascript function (such as JSON) when the user clicks that link.
So I thought, why don't I use my templating system to just autogenerate the javascript? For each link I want to generate, I generate a unique javascript function (DoItX where X is a unique integer for this page). Then instead of trying to pass arguments to my javascript function via onclick, I will insert my arguments as local variables for DoX. On link "X" I just say onclick="DoX()".
So I did this and viola it works! (it also helps me avoid the quote escaping hell I was in earlier). But I feel icky.
My question is, am I nuts? Is there an easier way to do this? I understand the implications that somehow somebody was able to change my templated local variable, ie:
var local = {TEMPLATED FIELD};
into something with a semicolon, inserting arbitrary javascript to the client. (and I'm trying to write code to be paranoid of this).
When is it ok (is it ever ok) to generate javascript from the server? Anything I should look out for/best practices?
Depending on your application generating JavaScript in your templating language can save a lot of time but there are pitfalls to watch out for. The most serious one being that it gets really hard to test your JavaScript when you don't have your full templating stack available.
One other major pitfall is that it becomes tempting to try and 'abstract' JavaScript logic to some higher level classes. Usually this is a sign that you will be shaving yaks in your project. Keep JavaScript login in JavaScript.
Judging from the little bit of information you have given it your solution seems sensible.
If you must generate javascript, I would suggest only generating JSON and having all functions be static.
It more cleanly separates the data, and it also makes it easier to validate to prevent XSS and the like.
JS generated from server is used in lots of areas. The following is the sample from a ASP.NET page where the JS script is generated by the framework:
<script src="/WebResource.axd?d=9h5pvXGekfRWNS1g8hPVOQ2&t=633794516691875000" type="text/javascript"></script>
Try to have reusable script functions that don't require regeneration; and 'squeeze' out the really dynamic ones for server-side generation.
If you want to feel better about it, make sure that most of your JavaScript is in separate library files that don't get generated, and then, when you generate code, generate calls to those libraries rather than generating extensive amounts of JavaScript code.
it's fine to generate JS from the server. just bear in mind not to fine too big a page from the server.
Generally speaking I avoid ever automatically generating JavaScript from a server-side language, though I do however; create JavaScript variables that are initialized from server-side variables that my JavaScript will use. This makes testing and debugging much simpler.
In your case I may create local variables like the following which is easy to test:
<script type='text/javascript' language='javascript'>
<!--
var FUNC_ARG_X = <%= keyX %>;
var FUNC_ARG_Y = <%= keyY %>;
var FUNC_ARG_Z = <%= keyZ %>;
//-->
</script>
<script type='text/javascript' language='javascript'>
<!--
function DoCleanCall(arg) {
// Whatever logic here.
}
//-->
</script>
now in your markup use:
<a href='#' onclick='DoCleanCall(FUNC_ARG_X);'>Test</a>
Now of course you could have embedded the server-side variable on the <a/> tag, however it is sometimes required that you refer to these values from other parts of your JavaScript.
Notice also how the generated content is in it's own <script> tag, this is deliberate as it prevents parsers from failing and telling you that you have invalid code for every reference you use it in (as does ASP.NET), it will still fail on that section only however.