Sandboxing JavaScript in Java App – Link Collection

The JVM is by design an insecure environment and it is generally difficult to run untrusted code in a sandboxed environment.

However, it seems that is relatively easy to sandbox JavaScript code running in Oracle Nashorn. The instructions are here. Strangely, this was not easy to find through a Google search.

Below I have listed some further sources on Sandboxing JavaScript and Java code. Although there is plenty of material on Rhino, I would not recommend using this engine. I think Nashorn has been designed with support for Sandboxed code in mind from the very beginning while in Rhino the functionality feels kind of bolted on.

UPDATE I have implemented two little libraries which takes care of the grunt work of sandboxing Nashorn and Rhino code in Java:

Nashorn Sandbox (on GitHub)

Rhino Sandbox (on Github)

Sandboxing JavaScript

Nashorn

Restricting Script Access to Specified Java Classes: From the Oracle Nashorn docs. Shows how to restrict access to specific Java classes.

Rhino

Class ContextFactory: Useful for monitoring and setting restrictions on Rhino code.

Method initSafeStandardObjects: Useful for creating sandboxed Rhino code.

Rhino Sandbox: A small library for sandboxing JavaScript code running in Rhino.

Sandboxing Rhino in Java: Blog post

Securing Rhino in Java6: Blog post

DynJS

Sandboxing JavaScript Execution in Java: Blog post

Sandboxing Java

Example Code Monitoring Threads: Example code how thread CPU usage can be monitored.

The Java Sandbox: A library for sandboxing any Java code. Might be useful to sandbox the Java code with runs the script.

Fix Firefox ‘Permission denied to access property document’

Problem

You are trying to load a script from a local file into a page displayed in Firefox (as can sometimes be useful for testing).

Firefox reports an error such as

Error: Permission denied to access property ‘document’

Error: Permission denied to access property ‘local’

Solution

This problem is caused by a security restriction that should normally be in place. However, you can temporarily disable this security feature as follows:

  • Enter the address ‘about:config’ in your Firefox
  • Search for ‘strict_’
  • Double click on the value column for the preference ‘security.fileuri.strict_origin_policy‘ to switch it from ‘true’ to ‘false’.

Remember to reenable the policy once your tests are done!

Sources

https://bugzilla.mozilla.org/show_bug.cgi?id=477201

https://support.mozilla.org/en-US/questions/1003768

CodeMirror 3 Indent All Lines / Autoformat

Problem

You have created an instance of a CodeMirror and initialized it with some text and would like to correct its indentation or you would like to give the user the option to ‘autoformat’ the text entered.

Solution

Iterate over all lines in the editor and indent them individually:

var e = CodeMirror.fromTextArea(textarea.get(0), {});

for (var i=0;i<e.lineCount();i++) { e.indentLine(i); }

This should indent all lines in your editor nicely:

Note that in CodeMirror 2 there was an autoformatter add-in which is not officially supported for CodeMirror 3.

Remove Duplicates from Array in CoffeeScript

Problem

You have an array in CoffeeScript, which contains equal elements multiple times such as:

[1,1,2,3,3]

You would like to have only unique values in the array. Thus, transform it into:

[1,2,3]

Solution

You can use the following method to accomplish such:

removeDuplicates = (ar) ->
  if ar.length == 0
    return []  
  res = {}
  res[ar[key]] = ar[key] for key in [0..ar.length-1]
  value for key, value of res

alert(removeDuplicates([1,2,3,3,4,4,5]));

References

This solution is based on this approach (with a few minor issues fixed).

Insert Text at Caret Position in Summernote Editor for Bootstrap

Problem

Using the very useful Summernote Editor component for Bootstrap, you would like to insert some text at the current caret position programmatically.

Solution

The Summernote API does not provide any dedicated methods for inserting text. However, that’s not a problem since we can use the JQuery/native DOM API to insert text into the editor. Thankfully, the content of the Summernote editor is nothing but vanilla HTML/DOM elements. Thus, we can insert text at the current cursor position as follows (if the Summernote editor is focused):

To Insert at the End of the Current Paragraph

$(document.getSelection().anchorNode.parentNode).append(“appended!”);

To Insert at the Current Cursor Position

var selection = document.getSelection();
var cursorPos = selection.anchorOffset;
var oldContent = selection.anchorNode.nodeValue;
var toInsert = "InsertMe!";
var newContent = oldContent.substring(0, cursorPos) + toInsert + oldContent.substring(cursorPos);
selection.anchorNode.nodeValue = newContent;

Note: You probably will have to work some magic with the document.getSelection() call. The problem is that once you would click a button or trigger the action in some other way, the selection would change. Thus, I save a reference to the document.getSelection() upon every focus and key press event on the editor.

Insert at Current Position (Alternative)

As suggested by Dexter in the comments below, you can also insert text as follows:

$(‘#summernote’).summernote('editor.saveRange');

// Editor loses selected range (e.g after blur)

$(‘#summernote’).summernote('editor.restoreRange');
$(‘#summernote’).summernote('editor.focus');
$(‘#summernote’).summernote('editor.insertText', 'This text should appear at the cursor');

References

MDN – Selection.anchorNode

Stackoverflow – Get caret position in contentEditable div

Stackoverflow – Inserting Text at Cursor Position using JS/JQuery

Stackoverflow – JQuery Plugin for Inserting Text at Caret

CoffeeScript Fat Arrow (=>) explained

Anyone who has worked with JavaScript for anything but a very short time will have come across the problem that the meaning of ‘this’ is often ambiguous at best. CoffeeScript attempts to mitigate this problem somewhat by introducing the Fat Arrow operator (=>). This operator can be used as a replacement for the thin arrow operator (->) used extensively in CoffeeScript for defining functions.

Unfortunately, it is not easy to understand what the fat arrow operator does.I hope the following rules provide some guidance on how to use this operator in CoffeeScript:

Rule 1: You Don’t Need the Fat Arrow If You Don’t Use: class, this, and @

If you are a beginner in JavaScript and/or CoffeeScript, I would recommend keeping your hands of the language constructs ‘this’, ‘class’ and ‘@’. You can implement any application you like without having to use these constructs and it will make your applications more robust and bug free.

Rule 2: Use the Fat Arrow when You Use @ in a Callback Definition in a Method

If you use classes in your code and you want to create a new anonymous function to be passed as a callback (such as to listen to an onclick event or to defined setTimeout function), define this function with the fat arrow operator. This will assure that you still have access to the methods and properties of the class you are working with.

The fat arrow will ‘override’ the default meaning of the @ operator as follows, to assure that ‘this’ refers to what we would expect it:

CoffeeScript

delayedAction = =>  
  alert(@messsage)

setTimeout(delayedAction, 100);

JavaScript

delayedAction = (function(_this) {
  return function() {
    return alert(_this.messsage);
  };
})(this);

setTimeout(delayedAction, 100);

Rule 3: Don’t Use Methods as Callbacks and Avoid the Fat Arrow Operator in All Other Circumstances

There is one more use case for the Fat Arrow operator, which is that it has a special meaning when used for the definition of class methods. This is useful when the methods of a class are to be passed as a callback. I personally don’t think that’s a very useful feature and it’s better to define an anonymous function to handle a callback and then call a method of your class/object from within this callback. Following this rule enables us not having to worry about whether to define a method with a thin or fat arrow – which is otherwise tricky since the right choice here is external to the class we are writing.

More Reading

Karl Seguin – Ten Features I Like About CoffeeScript

Michael Kramer – The Simplified Fat Arrow Guide for CoffeeScript

Azat Mardanov – Understanding Fat Arrows (=>) in CoffeeScript

Giang Nguyen – Coffeescript: Fat arrow vs thin arrow

Embed HTML Code in JavaScript File

Problem

You would like to include HTML code as a String in a JavaScript file.

Solution

Firstly, load the HTML code into a JavaScript variable (e.g. by using jQuery.ajax()).

$.ajax({url: 'http://mydomain.com/htmlfile.html'})

.done(function(html) {

Then apply the following two simple regular expressions on the html code to generate valid JavaScript code.

var safeHtml = html

.replace(/\n/g, "\\n")

.replace(/\"/g, "\\\"")

You can use this String now to build a JavaScript file:

var myScript = 'var html="'+safeHtml+'";';

 

JavaScript and JSON Essentials (Packt) Review

JavaScript and JSON Essentials‘ by Packt publishing is a hands-on guide to developing JavaScript/PHP based web applications while using the JSON data format. This review of the book contains a quick summary of the contents as well as points to consider if you think of purchasing the book.

Overall, this as an easy to read book suited for novices in web development, packed with examples and easy to follow step-by-step instructions. However, advanced JavaScript developers will be familiar with most of the concepts covered in the book.

Contents

Chapter 1: JavaScript Basics

Explains the very basics of JavaScript, such as how to embed a script in a webpage, simple expressions (3+4), arrays and objects.

Chapter 2: Getting Started with JSON

Goes through the fundamental rules of JSON documents and how to access the data they contain in JavaScript applications.

Chapter 3: Working with Real-time JSON

Goes through an example of processing a complex JSON document, a collection of employees with their personal and employment details. Specifically, to query data from the document such as retrieving the positions of employees and to modify data.

Chapter 4: AJAX Calls with JSON Data

Shows how to set up a simple web server under a Linux (LAMP) and Windows (ASP.NET) environment. Then, how to host a simple PHP script dynamically rendering JSON data and using XMLHttpRequest to access the data from this script from a JavaScript application.

Chapter 5: Cross-domain Asynchronous Requests

This chapter firstly expands the PHP script and JavaScript application developed in the previous chapter. Specifically, by allowing to pass query parameters to the PHP script. Then, an example is shown how to load a JSON document through JSONP from the site reddit.

Chapter 6: Building the Carousel Application

Shows how to develop a small example application in which student records are retrieved from a server and displayed in a web browser.

Chapter 7: Alternate Implementations of JSON

Portrays numerous ways in which JSON data is used such as in PHP Composer and for Node.js package manager NPM. Briefly compares JSON with the data definition format YAML.

Chapter 8: Debugging JSON

Introduces numerous tools that can aid in developing JavaScript applications such as Firebug and tools to validate (only syntax) and format JSON documents.

The Good

  • Provides a good introduction to developing simple applications with JavaScript and PHP which utilize JSON data.
  • The book is overall well organized and it is easily understandable what is covered in the chapters.
  • There are plenty of examples and step-by-step instructions
  • The PDF version of the book is easy to navigate, with helpful bookmarks, which allow to browse the table of contents and hyperlinks throughout the document.

Caveat Emptor

  • Don’t expect to become a grandmaster of JavaScript after reading the JavaScript intro of the book. It’s around 14 pages and only meant to give a brief idea of JavaScript. If you are new to JavaScript, consider a complementary book such as Object-Oriented JavaScript or JavaScript The Good Parts.
  • This book, as its title specifies covers the ‘Essentials’ of JavaScript and JSON. Thus it’s a good starting point to become familiar with these technologies but does not contain more advanced or nuanced discussions, such as good design practices for JSON documents, performance issues or tradeoffs in using JSON.

Disclaimer: Thanks to Packt Publishing for providing a free review copy of this book!

Render HTML from Object with CoffeeKup

CoffeeKup allows to render HTML from multiple sources:

  • A String containing valid CoffeeScript code
  • A JavaScript/CoffeeScript object arranged according to CoffeeKup rules

To render HTML from a String is quite straightforward and documented on the CoffeeeScript reference: you can use the methods .compile and .render as documented there.

However, to render HTML from a JavaScript/CoffeeScript object can also come in handy, to create a tight link between your logic and markup. The .render method is not only able to process a String but is also able to process a certain kind of Object as well.

Here find two examples of how to render JavaScript and CoffeeScript objects into HTML:

JavaScript Object

CoffeeKup.render(function() {

  return div({ class: 'mydiv' }, 'Hello World');

});

which results in:

"<div class='mydiv'>Hello World</div>"

CoffeeScript Object

CoffeeKup.render(div 'mydiv', ->'Hello World'<span style="line-height: 1.5em;">);

resulting in the same HTML as above.

Touch and Click in jQuery (without jQuery Mobile)

Problem

One of the most common things I do with JQuery is to attach click event listeners to buttons, links and other elements as follows:

$(“.class”).click(function(evt) {});

Unfortunately, I found that, while this approach works well for Desktop browsers, the user interaction on touch-enabled devices feels very awkward and sluggish.

Solution

Since this problem is of relevance for every mobile web application, numerous solutions have been proposed. All mobile UI JavaScript frameworks I know of provide built in support for ‘tab’ events, as opposed to ‘click’ events.

However, often we would just like to support being able to interact with simple buttons on our page regardless of whether a user accesses the site through a desktop or mobile browser; ideally, without adding another more or less ‘heavy’ framework to our site.

Luckily, jQuery Mobile is built in a very modular way and we can extract the particular component of the framework to support good support for tabs and clicks. Head to http://jquerymobile.com/download-builder/ and only check the ‘Touch’ component under Events.

Then, let the jQuery Mobile site build your download and add it to your page. For a quick test, you can also use the script provided below.

Next, we can rewire all calls to $(…).click() using the following snippet:


<script src="http://u1.linnk.it/qc8sbw/usr/apps/textsync/upload/jquery-mobile-touch.value.js " ></script>

<script>

$.fn.click = function(listener) {

    return this.each(function() {

       var $this = $( this );

       $this.on(‘vclick’, listener);

    });

};

</script>

Now, when you register an event listener in your app using $(…).click(), the respective element should be pleasant to use for both desktop and mobile users.

References

The Current State of (Touch) Events

Tap vs. Click: Death by Ignorance