David Tuite
David Tuite

Reputation: 22643

How can I translate this syntax to CoffeeScript (js2coffee doesn't work)?

Basically I need to translate the following piece of JavaScript into CoffeeScript.

location.href = "javascript:(" + function() {
  window.onbeforeunload = function() {
    notifyBackground(collectData());
    return undefined;
  };
} + "){}";

The return "undefined" is important because the browser will ask the user to confirm that they want to leave the page if I remove it.

You might be wondering wtf I'm doing. Basically, it's a location hack for Firefox extension development.

I've tried doing the following:

location.href = "javascript:(" + ->
  window.onbeforeunload = ->
    notifyBackground(collectData())
    return undefined
+ ")()"

But that turns into:

location.href = "javascript:(" + function() {
  return window.onbeforeunload = function(e) {
    notifyBackground(collectData());
    return void 0;
  };
};
return +")()";

Using js2coffee.org gives me this:

location.href = "javascript:(" + ->
  window.onbeforeunload = ->
    notifyBackground collectData()
    "undefined"
 + "){}"

If I run that through CoffeeScript I get this JS output (which is wrong).

location.href = "javascript:(" + function() {
  return window.onbeforeunload = function() {
    notifyBackground(collectData());
    return "undefined";
  };
};
return +"){}";

Upvotes: 2

Views: 766

Answers (2)

phenomnomnominal
phenomnomnominal

Reputation: 5515

Is this close enough?

location.href = "javascript:(#{-> 
  window.onbeforeunload = -> 
    notifyBackground(collectData())
    `undefined`
  return
}){}"

Compiles to:

location.href = "javascript:(" + (function() {
  window.onbeforeunload = function() {
    notifyBackground(collectData());
    return undefined;
  };
}) + "){}";

Note the backticks around the undefined to avoid the void 0, just in case that makes a difference (And I'm not sure if it does?)

EDIT

In the Chrome console undefined == void 0 is true, so maybe the

`undefined`

could simply be:

undefined

Upvotes: 3

pkurek
pkurek

Reputation: 606

Try this site http://js2coffee.org/ its a js to coffee (and backwards) converter.

Upvotes: 1

Related Questions