Cross-Domain Requests in GWT with JSONP

GWT RPC is built upon AJAX requests and thus is subject to the Same-Origin Policy. However, it is really easy in GWT (as well as in other JavaScript applications) to circumvent this policy using a method called JSON-with-padding (JSONP).

Unfortunately, there are a couple of issues one needs to consider before utilizing JSON-P:

Amount of Data Send from Client to Server

The biggest limitation of JSONP is that it uses GET and not POST requests. Thus, all data send from the client to the server needs to be encoded as URL query parameters such as:

http://myserver.com/myrpctarget?data_from_client=lotsofdatafromclient

These URL parameters can only hold a limited amount of data. I couldn’t find a conclusive upper limit on this, but most sensible suggestions seem to indicate that parameters should be limited to between 2,000 or 4,000 bytes. Please note that many sources here discuss the limit of characters which can be put into a browsers address bar. This limit is not the same as the limit for GET requests triggered from within JS code.

Reliance on GWT RPC

It is a non-trivial (but not impossible – I’ve done it!) endeavor to channel GWT RPC requests through JSONP. Thus, if your application is deeply dependent on GWT RPC, it will probably involve a lot of work to make it JSONP ready. Good news is that if you use the Request Builder API things will be far easier.

Other than these two issues there is really nothing stopping you from writing GWT client applications, which can communicate with multiple servers. I believe that this decoupling from client and server is far more valuable than the added security derived from restricting requests to one domain. After all, the browser is a client application which is by design meant to communicate with many different servers. If you have a choice, consider the two factors above and architect your GWT applications from the very beginning in a way which enables JSONP requests.

Resources

GWT JavaDoc – JsonpRequestBuilder

Wikipedia – JSONP

GWT 2, JSONP and Javascript Overlays with JsonpRequestBuilder

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