JavaScript Functions for Inserting Blocks in Roam

At the end of this snippet I include some helpful javascript functions for accessing and inserting pages and blocks in Roam Research. Hope you find these useful!

getPage(page): returns the uid of a specific page in your graph. page: the title of the page.

getOrCreatePage(page): returns the uid of a specific page in your graph, creating it first if it does not already exist. page: the title of the page.

getBlockOnPage(page, block): returns the uid of a specific block on a specific page. page: the title of the page. block: the text of the block.

createBlockOnPage(page, block, order): creates a new top-level block on a specific page, returning the new block’s uid. page: the title of the page. block: the text of the block. order: (optional) controls where to create the block, 0 for top of page, -1 for bottom of page.

getOrCreateBlockOnPage(page, block, order): returns the uid of a specific block on a specific page, creating it first as a top-level block if it’s not already there. page: the title of the page. block: the text of the block. order: (optional) controls where to create the block, 0 for top of page, -1 for bottom of page.

getChildBlock(parent_uid, block): returns the uid of a specific child block underneath a specific parent block. parent_uid: the uid of the parent block. block: the text of the child block.

createChildBlock(parent_uid, block, order): creates a new child block underneath a specific parent block, returning the new block’s uid. parent_uid: the uid of the parent block. block: the text of the new block. order: (optional) controls where to create the block, 0 for inserting at the top, -1 for inserting at the bottom.

getOrCreateChildBlock(parent_uid, block, order): returns the uid of a specific child block underneath a specific parent block, creating it first if it’s not already there. parent_uid: the uid of the parent block. block: the text of the child block. order: (optional) controls where to create the block, 0 for inserting at the top, -1 for inserting at the bottom.

Caution ⚠️ If multiple blocks with the same text exist on the page, these functions may return the uid of the wrong block.

To use these functions in your Roam database, create a block with the string {{[[roam/js]]}}, create a code block by typing triple-backticks (```), paste the above JavaScript into the code block, and click “Yes, I know what I’m doing.”

As a reminder, you get the result of an async function with await, e.g.

let uid = await getOrCreateBlockOnPage(
    "February 12, 2020", "Fleeting TODOs:")

The create- and getOrCreate- functions are async, whereas the pure get- functions are regular functions. So, be sure to use await accordingly.

Discussion 💬

Related