All posts

Branching and Looping Logic for Complex Web Forms in Broma

Branching and Looping Logic for Complex Web Forms in Broma

Why Branching and Looping Matter

Most repetitive web tasks are not linear. A checkout flow may show different upsell options depending on the cart total. A support dashboard might require you to iterate over a dynamic list of tickets. Broma lets you model that variability with Branch and Loop steps, turning a single recorded sequence into a resilient, data‑driven workflow.

Core Concepts in Broma

Branch step

A Branch evaluates a JavaScript expression. If the result is truthy the workflow follows the True path; otherwise it follows the False path. The expression can read any variable that exists in the run context — page text, extracted attribute, or a value you stored earlier.

Loop step

A Loop repeats a block of steps for each item in an array. You supply the array (often the result of a Read text or Get elements step) and Broma exposes the current item as item and the index as index inside the loop body.

Variables

Every step can write to the run‑time variable store (Set variable). Later steps, including Branch conditions and Loop iterators, read those variables with the {{varName}} syntax or directly in JavaScript.

Building a Conditional Branch

  1. Open the target page – Open url → https://example.com/checkout.
  2. Read a decisive element – Read text on the element that shows the cart total, store as cartTotal.
  3. Add a Branch step – Condition:
Number({{cartTotal}}.replace(/[^\d.]/g, '')) >= 100

True path: click the “Free shipping” banner. False path: continue to standard shipping selection. 4. Continue the workflow – Both paths converge on the “Place order” click.

Tip: Keep the condition pure JavaScript. Avoid side effects; the expression runs in a sandboxed context each time the branch is evaluated.

Looping Over a List of Items

Imagine a product‑grid page where each row has an “Add to cart” button. You want to add the first five items.

  1. Get elements – Get elements with selector css:.product-row → stores array in rows.
  2. Add a Loop step – Iterator: {{rows}}. Limit iterations to 5 by adding a Break step inside the loop when index === 4.
  3. Inside the loop:
    • Click on item.querySelector('button.add-to-cart').
    • Wait for element confirming the cart badge updates.
    • Set variable addedCount = {{addedCount}} + 1 (initialize addedCount to 0 before the loop).
  4. After the loop – Proceed to checkout.
// Example of a Break condition placed as a Branch inside the loop
{{index}} >= 4

Combining Branches and Loops: Real‑World Scenario

Order‑processing bot – A marketplace seller needs to confirm each order, but the confirmation UI differs for “digital” vs “physical” goods.

  1. Fetch order list – API call (via a short JS snippet) returns orders array.
  2. Loop over orders.
  3. Inside loop – Open url to order detail page.
  4. Branch on order.type (extracted from a hidden data attribute):
    {{order.type}} === 'digital'
    
    True → click “Deliver digitally”, fill license key field. False → click “Print shipping label”, wait for PDF download.
  5. Set variable processed = {{processed}} + 1.
  6. After loop – Write summary to a local CSV using a Run JavaScript step:
const fs = require('fs');
fs.writeFileSync('processed_orders.csv', 'OrderID,Type\n' + {{orders}}.map(o => `${o.id},${o.type}`).join('\n'));

Debugging Tips

  • Run logs – Every Branch and Loop logs the evaluated condition and the current item/index. Open the run history panel to see which path fired.
  • Breakpoints – Right‑click any step → Add breakpoint. Execution pauses before the step, letting you inspect variables in the console.
  • Console.log in JS steps – console.log('cartTotal:', {{cartTotal}}); appears in the run log output tab.
  • Limit loop size during development – Add a temporary Branch at the top of the loop: {{index}} < 2 to test only the first two iterations.

Best Practices

Practice Reason How to implement in Broma
Stable selectors Prevent breakage when markup changes Use data‑attributes ([data-test-id]) or relative XPath (//button[contains(., 'Add')]).
Explicit variable naming Makes conditions readable Prefix with domain: order_, cart_, ui_.
Guard loops Avoid infinite runs on empty arrays Add a Branch before Loop: {{rows}}.length > 0.
Separate concerns Easier maintenance Put each logical phase (login, navigation, processing) in its own Sub‑workflow and call via Run workflow step.
Version control Track changes across team Export workflow JSON, commit to git; Broma’s Import/Export menu handles this.

Example Workflow (Export Snippet)

Below is a trimmed JSON export showing the Branch and Loop structure. You can paste it into Broma’s Import dialog to see the steps instantly.

{
  "name": "ProcessOrders",
  "steps": [
    {"type": "RunJavaScript", "code": "const orders = await fetch('/api/orders').then(r=>r.json()); return orders;", "outputVar": "orders"},
    {"type": "Loop", "iterator": "{{orders}}", "steps": [
      {"type": "OpenUrl", "url": "https://market.example.com/order/{{item.id}}"},
      {"type": "ReadAttribute", "selector": "[data-order-type]", "attr": "data-order-type", "outputVar": "orderType"},
      {"type": "Branch", "condition": "{{orderType}} === 'digital'", "trueSteps": [
        {"type": "Click", "selector": "button.digital-deliver"},
        {"type": "Type", "selector": "input.license-key", "text": "{{item.licenseKey}}"}
      ], "falseSteps": [
        {"type": "Click", "selector": "button.print-label"},
        {"type": "WaitForDownload", "pattern": "*.pdf"}
      ]},
      {"type": "SetVariable", "name": "processed", "value": "{{processed}} + 1"}
    ]}
  ]
}

Next Steps

  1. Prototype a single branch on a page you already automate. Verify the condition logic with a few manual runs.
  2. Add a loop around a repetitive click‑sequence (e.g., pagination, table rows).
  3. Combine them in a sub‑workflow and share the export with teammates for review.
  4. Monitor run logs for a week; adjust selectors or conditions only when a genuine page change occurs.

By mastering branches and loops you turn fragile linear scripts into adaptable automations that survive UI tweaks and handle real‑world variability — exactly the kind of resilience Broma is built for.