# Browser examples — `posprintUrl()`

See [docs/POSPRINT-URL.md](../../docs/POSPRINT-URL.md) for URL format and size limits.

Browsers cannot read arbitrary paths on disk. “Local file” here means a user-selected `.pos` file via `<input type="file">`, or JSON fetched from your server.

Requires `CompressionStream('deflate-raw')` (recent Chromium, Firefox, Safari).

```html
<script type="module">
  import { posprintUrl } from './posprint_url.js';
</script>
```

## From an object

Build the document in JavaScript and open the link:

```html
<button id="print">Print</button>
<script type="module">
  import { posprintUrl } from './posprint_url.js';

  document.getElementById('print').addEventListener('click', async () => {
    const url = await posprintUrl({
      version: 1,
      metadata: {
        title: 'Barcode demo',
        page_width_mm: 53,
        chars_per_line: 32,
      },
      body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
    });
    window.location.href = url;
  });
</script>
```

Or render a link without navigating immediately:

```js
const url = await posprintUrl({ /* … */ });
const a = document.createElement('a');
a.href = url;
a.textContent = 'Print receipt';
document.body.append(a);
```

## From a local `.pos` file (user picks file)

```html
<input type="file" id="pos-file" accept=".pos,application/json" />
<a id="print-link" hidden>Print</a>

<script type="module">
  import { posprintUrl } from './posprint_url.js';

  document.getElementById('pos-file').addEventListener('change', async (ev) => {
    const file = ev.target.files?.[0];
    if (!file) return;

    const json = await file.text();
    const url = await posprintUrl(json);

    const link = document.getElementById('print-link');
    link.href = url;
    link.hidden = false;
  });
</script>
```

## From a file on your server

If the `.pos` lives on the same site, fetch it and pass the JSON string:

```js
const res = await fetch('/templates/receipt.pos');
const json = await res.text();
const url = await posprintUrl(json);
window.location.href = url;
```

## Length warning

On Windows, keep the full URL under ~7000 characters so the OS can launch posprint. Prefer short templates and `@image https://…` for logos.
