Issues with modern JavaScript syntax in “run JS in browser” action

KM v11 introduced “modern JavaScript syntax” in the “execute JavaScript in Front Browser” (and related) actions. It also says that there is a toggle to go back to the pre-v11 style of JS. However, in the right click menu on that action, unless I'm missing something, I don't see such a toggle.

image

I ask because prior to v10 I already used (() => { /* stuff */})() in my JS actions in order to achieve the same effect as the “modern syntax” in v11. However, now when I try to run an action with this “self-calling” syntax, it fails with TypeError: Object is not a function (near '...}...'). I assume that the modern syntax is wrapping (() => {})() in something that causes JS to parse a function as an object and then trying to call it.

Thanks for any help.

I think you will find that the reference on the wiki page action:Execute a JavaScript For Automation [Keyboard Maestro Wiki] is not to a right-click menu, but to the the popup menu next to the script.

You can turn Modern Syntax on or off in the popup menu next to the script.

( Perhaps worth deleting the bug tag, to avoid later confusion ? )


If you are testing your code in an editor using an IIFE wrapper:

(() => {
    
     // KM Code here

})();

then when you deploy to the Execute JavaScript action (using the modern syntax for easier and safer access to KM variables), you can just comment out the first and last lines:

//(() => {
    
     // KM Code here

//})();

Or, of course – possibly quicker to edit and reverse – you can just precede your IIFE with a return keyword:

return (() => {
    
     // KM Code here

})();
1 Like

Thanks, very helpful! I had no idea that that popup existed (I guess I assumed it would collapse the text input and never clicked it?). (Also, those backslashes should be forward (\\//), but nbd.)

The return trick works, although I am still curious about what KM was doing that made a IIFE fail to work. It was not simply inserting a function around the code, because (function() { (() => {})() })() is perfectly valid.

Thanks again. I will start to migrate away from my own IIFE now that KM includes it and I know how to toggle it.

1 Like