This is a quick walkthrough of two powerful approaches you can take to debug your JavaScript code in your Smart Blocks in Roam.
Browsers nowadays have developer tools included.
On Chromium browsers you'll find developer tools under more tools in the browser menu or you can also use the shortcut Option + ⌘ + J (on macOS), or Shift + CTRL + J (on Windows/Linux).
In Safari developer tools are under the Develop menu. If you don’t see the Develop menu in the menu bar, choose Safari > Preferences, click Advanced, then select “Show Develop menu in menu bar.”
In this article I assume you already have Roam42 installed. If not, you can see instructions for downloading and installing Roam42 here.
Breakpoint in 42SmartBlock code
You need to apply a small trick to be able to place a breakpoint within your javascript code you are running in your #42SmartBlock.
Load Roam into your browser window, then open Developer Tools of your browser. Click the Sources Tab. Right click the top of the sources tree and select "Search in all files...". In the search box enter the following search term:
Function(scriptToRun.toString()) |
You should find two instances of this in the roam42 source code. One for the <%JAVASCRIPT: %> (or <%J %> command, the other for the <%JAVASCRIPTASYNC: %> (or <%JA %>) command. Place breakpoints on these lines. For the async function place the breakpoint on the new AsyncFunction call not on the await call.
When you run your SmartBlock in Roam, the browser will break the execution of the javascript when it hits the line with the breakpoint. At this point click the "Step into next function call" button. You'll be taken into the javascript code of your 42SmartBlock. Place a breakpoint within your Smart Block to the location you want to analyze, and press "Resume script execution". The script will resume until it reaches your second breakpoint. At this time you can use developer tools to inspect values of variables, to look at the call stack, etc.
Console Log
console.log('message');
|
Your message may be any expression that resolves to a string.
Using the console log is an excellent way to monitor the operation of your Smart Block, such that you have an execution trace in the console log when something surprising happens and you need to understand why it may have happened.
Do you know how to clear a script cache, or making sure only one versiĆ³n of a ```javascript``` is running?
ReplyDeleteI have a var update = setInterval(function () { }, 500);
So when I try to debug, I get more than one result.
I've found the same recently. somehow with a recent update Roam seems to execute roam/js scripts twice on loading. My workaround is to delare a global variable in my script and check if the variable is there. Looks like a hack, but works...
ReplyDeleteif (typeof window.myXYZFlag === 'undefined') {
window.myXYZFlag = true;
var update = setInterval(function () { }, 500);
}