Open in a new tab

Load a same-origin JSON file through a small ajax client with typed HTTP errors, broadcast a message to the other open tabs of the page, and show the online / offline status.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Any page that reads data from its own origin, wants a clear error when the file or the network is missing, and keeps several tabs in step (a login, a setting, a "new version" notice).

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html, main.js and data.json next to each other and open index.html through that server; open it twice to see the broadcast. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Point api at your own origin or API base and keep the paths relative.

What it shows

  • ajax(location.origin, { timeout }): ajax resolves to a factory, and a relative endpoint needs an absolute base. api.get(path) parses JSON from the content type; a 404 rejects with api.HttpError carrying status.
  • broadcastChannel.isSupported(), create(name), post(data), on(fn): a tab receives the other tabs' posts, never its own.
  • network.onChange(fn, { immediate: true }) for online / offline.
  • No absolute URL anywhere: the data path is derived from the page URL.

Code

main.js

javascriptApache-2.060 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { ajax } from '@awacloud/fw/dom/net/ajax.js';
import { broadcastChannel } from '@awacloud/fw/dom/net/broadcastChannel.js';
import { network } from '@awacloud/fw/dom/net/network.js';

fw.runtime.registerAllDeep([ajax, broadcastChannel, network]);
const CHANNELS = fw.runtime.resolve('broadcastChannel');
const NETWORK = fw.runtime.resolve('network');

// `ajax` resolves to a factory: give it the origin, then request paths.
export const api = fw.runtime.resolve('ajax')(location.origin, { timeout: 5000 });
/** The path of a file next to this page, wherever the page is served from. */
export const DATA_PATH = new URL('./data.json', location.href).pathname;

/** @param {string} id @param {string} value */
const show = (id, value) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = value; };

/**
 * @param {string} path
 * @returns {Promise<{ sku: string, name: string }[]>}
 */
export async function loadProducts(path = DATA_PATH) {
    const list = /** @type {HTMLElement} */ (document.getElementById('products'));
    try {
        const data = await api.get(path);
        list.replaceChildren(...data.products.map((/** @type {{ sku: string, name: string }} */ p) => {
            const li = document.createElement('li');
            li.textContent = `${p.sku}: ${p.name}`;
            return li;
        }));
        show('load-status', `${data.products.length} products loaded`);
        return data.products;
    } catch (err) {
        // HttpError carries the status; a network failure has none.
        const status = err instanceof api.HttpError ? `HTTP ${err.status}` : /** @type {Error} */ (err).message;
        show('load-status', `Could not load ${path}: ${status}`);
        return [];
    }
}

/** Cross-tab messages: same origin, same channel name, every open tab. */
export const CHANNEL = 'examples-dom-net';
export const channel = CHANNELS.isSupported() ? CHANNELS.create(CHANNEL) : null;
if (channel) {
    const received = /** @type {HTMLElement} */ (document.getElementById('received'));
    channel.on((/** @type {{ text: string }} */ data) => {
        received.appendChild(document.createElement('li')).textContent = String(data.text);
    });
}
const form = /** @type {HTMLFormElement} */ (document.getElementById('send'));
const message = /** @type {HTMLInputElement} */ (document.getElementById('message'));
form.addEventListener('submit', (event) => {
    event.preventDefault();
    if (channel) channel.post({ text: message.value, at: Date.now() });
    message.value = '';
});

NETWORK.onChange((online) => show('online', online ? 'online' : 'offline'), { immediate: true });
await loadProducts();

index.html

htmlApache-2.031 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Fetch JSON, talk to other tabs, watch the connection</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Fetch JSON, talk to other tabs, watch the connection</h1>
    <p>Connection: <output id="online"></output></p>
    <h2>Products from <code>./data.json</code></h2>
    <p id="load-status" aria-live="polite"></p>
    <ul id="products"></ul>
    <h2>Other tabs</h2>
    <form id="send">
      <label for="message">Message to every open tab of this page</label>
      <input id="message" type="text" autocomplete="off" required>
      <button type="submit">Send</button>
    </form>
    <ol id="received" aria-live="polite" aria-label="Messages received"></ol>
  </main>
</body>
</html>

data.json

jsonApache-2.07 lines

{
  "products": [
    { "sku": "fw-001", "name": "Framework core", "price": 0 },
    { "sku": "fw-002", "name": "Crypto tier", "price": 0 },
    { "sku": "fw-003", "name": "Examples", "price": 0 }
  ]
}