# Share, clipboard and print - JavaScript bridge API

> The Android share sheet, the system clipboard, text another app shared into yours, and the print dialogue.

- **Applies to:** AppMint
- **Source:** extracted from the app runtime and its per-method example files; this page is generated from them.
- **HTML:** https://freewebtoapk.com/docs/api/share

### `navigator.clipboard`

```js
navigator.clipboard.writeText / readText (and write / read)
```

**Example**

The standard Clipboard API, answered by the phone's real clipboard inside the app.

**Returns:** `writeText(text)` → a Promise that resolves when copied and rejects with a `NotAllowedError` otherwise. `readText()` → a Promise with the clipboard text (`""` when empty). `write([item])` / `read()` → Promises, as in the standard. **Needs:** nothing. Installed at document start, so a check made while your page parses already sees it.

**Copy:**

```js
async function copyLink(link) {
  if (!(navigator.clipboard && navigator.clipboard.writeText)) { alert('Copy is not available'); return; }
  try {
    await navigator.clipboard.writeText(link);
    showMessage('Link copied');
  } catch (e) {
    showMessage('Could not copy');
  }
}
```

**Paste** - from a tap:

```js
document.getElementById('paste').onclick = async function () {
  try {
    var text = await navigator.clipboard.readText();
    document.getElementById('input').value = text;
  } catch (e) {
    showMessage('Could not read the clipboard');
  }
};
```

**Copy an image** (for example a QR code drawn on a canvas) with `ClipboardItem`:

```js
async function copyCanvas(canvas) {
  if (!(navigator.clipboard && navigator.clipboard.write && window.ClipboardItem)) {
    alert('Copying images is not available here');
    return;
  }
  var blob = await new Promise(function (r) { canvas.toBlob(r, 'image/png'); });
  try {
    await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
    showMessage('Image copied');
  } catch (e) {
    showMessage('Could not copy the image');
  }
}
```

**Notes:** In the app, `writeText`/`readText` call `WebToApk.copyToClipboard` and `WebToApk.readClipboard`. `write()` takes the first `ClipboardItem` only and supports `text/plain`, `text/html` and one image (up to 16 MB; an image wins over text in the same item). `read()` resolves to `[item]` with the clipboard's text, HTML or image (`[]` when it is empty). Only the app's own pages can read it: a foreign website opened inside the app is refused (`NotAllowedError`). Read it on a user tap - Android 12+ shows a "pasted from clipboard" notice. In a browser the same code works with the browser's own permission rules.

### `navigator.share`

```js
navigator.share(data) / navigator.canShare(data)
```

**Example**

The standard Web Share API, made to work inside the app: text and links open the Android share sheet, and `files` are shared as real files (WhatsApp, Gmail, Drive…).

**Returns:** `navigator.share` → a Promise that resolves when the sheet opens (it does not tell you which app was picked). `navigator.canShare` → `true`/`false`. **Needs:** nothing. Installed at document start, so a check made while your page parses already sees it.

**Text and a link:**

```js
async function shareItem(item) {
  if (!navigator.share) { alert('Sharing is not available here'); return; }
  try {
    await navigator.share({ title: item.name, text: 'Look at this', url: item.link });
  } catch (e) { /* in a browser: AbortError when the user closes the sheet */ }
}
```

**Files** - check with `canShare` first:

```js
async function sharePdf(blob) {
  var file = new File([blob], 'invoice.pdf', { type: 'application/pdf' });
  var data = { files: [file], title: 'Invoice', text: 'Invoice for March' };
  if (!(navigator.canShare && navigator.canShare(data))) {
    alert('File sharing is not available here');
    return;
  }
  try {
    await navigator.share(data);
  } catch (e) { console.log('Share failed', e); }
}
```

**Notes:** In the app `title` becomes the subject, and `text` + `url` are sent as one text. With `files`, each file is read in the page and sent as base64 (`WebToApk.shareFiles`), so keep files to a few MB. If the share sheet cannot open, the files are saved as downloads instead and the promise still resolves. `canShare` returns `true` for any text share. AI-built apps can use `share` from `@/lib/appmintNative`.

### `window.print`

```js
window.print()
```

**Example**

The standard print call, made to work inside the app: it opens Android's print screen, where the user prints on paper or saves a PDF.

**Returns:** nothing. **Needs:** nothing.

```js
document.getElementById('print-receipt').onclick = function () {
  window.print();
};
```

Hide the app's controls on paper with a print stylesheet:

```html
<style>
  @media print {
    nav, .toolbar, button { display: none !important; }
    body { background: #fff; color: #000; }
  }
</style>
```

**Notes:** `window.print()` prints the main page as it is drawn now. A same-origin `<iframe>` - the hidden iframe a print library fills with a receipt and calls `iframe.contentWindow.print()` on, or an iframe page calling its own `window.print()` - prints THAT iframe's document (see `__printHtml`). A cross-origin iframe cannot be printed from the page. The replacement exists before the page's first script. `beforeprint` cannot be cancelled (in any browser).

### `__clipboardRead`

```js
window.WebToApk.__clipboardRead(): String
```

navigator.clipboard.read(): `{parts:[{type, text|base64}]}`. Same reach as readClipboard() in this shell (which has no origin gate).

**Example**

Internal transport behind `navigator.clipboard.read()`. Pages use the standard API; never call this directly - the `__` methods may change without notice.

**Returns:** `{parts:[{type, text|base64}]}` - the same reach as `readClipboard()` in this app. **Needs:** nothing to switch on.

**Use the public API:**

```js
canvas.toBlob(async (png) => {
  await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })]);
});
const [item] = await navigator.clipboard.read();
if (item && item.types.includes('image/png')) preview(await item.getType('image/png'));
```

**Notes:** Android 12+ shows its own "pasted from your clipboard" message when an app reads the clipboard.

### `__clipboardWrite`

```js
window.WebToApk.__clipboardWrite(partsJson: String): Boolean
```

navigator.clipboard.write(): [partsJson] is `[{type, text}|{type, base64}]` for one ClipboardItem - text/plain, text/html, or an image that is copied as a content URI.

**Example**

Internal transport behind `navigator.clipboard.write([ClipboardItem])`. Pages use the standard API; never call this directly - the `__` methods may change without notice.

**Returns:** `true` when the clip was placed. **Needs:** nothing to switch on.

**Use the public API:**

```js
canvas.toBlob(async (png) => {
  await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })]);
});
const [item] = await navigator.clipboard.read();
if (item && item.types.includes('image/png')) preview(await item.getType('image/png'));
```

**Notes:** Text, HTML and one image per item. The image is copied as a content URI through the app's FileProvider, so it pastes into WhatsApp, Gmail or Keep.

### `__printHtml`

```js
window.WebToApk.__printHtml(html: String, baseUrl: String, title: String)
```

Prints [html] - a same-origin iframe's serialised document, sent by the `window.print()` shim ([PrintShim]) - through an offscreen WebView at [baseUrl], because the main WebView's print adapter can only print the whole page. [title] names the print job ("<App name> Document" when blank).

**Example**

Internal transport behind printing an iframe: `iframe.contentWindow.print()` (and an iframe page's own `window.print()`) sends that iframe's document here, and the app prints it through Android's print screen. Pages use the standard calls; never call this directly.

**Returns:** nothing. **Needs:** nothing.

The receipt pattern this makes work - a hidden iframe filled with just the receipt:

```js
function printReceipt(order) {
  var frame = document.createElement('iframe');
  frame.style.display = 'none';
  document.body.appendChild(frame);
  var doc = frame.contentWindow.document;
  doc.open();
  doc.write('<html><head><title>Receipt ' + order.id + '</title>' +
            '<style>body{font:14px sans-serif} td{padding:2px 8px}</style></head><body>' +
            '<h2>Receipt ' + order.id + '</h2><table>' +
            order.lines.map(function (l) { return '<tr><td>' + l.name + '</td><td>' + l.price + '</td></tr>'; }).join('') +
            '</table></body></html>');
  doc.close();
  frame.contentWindow.print();   // prints the RECEIPT, not the page behind it
  setTimeout(function () { frame.remove(); }, 1000);
}
```

**Notes:** Arguments are `(html, baseUrl, title)`: the iframe's serialised document, the address its relative links resolve against (the page's own address for an `about:blank` iframe), and the print job name (the iframe's `<title>`, else the page's). The snapshot is taken when `print()` is called - scripts inside it do not run again - and `beforeprint` / `afterprint` fire on the iframe's window around it. A cross-origin iframe cannot be printed from the page.

### `clearSharedText`

```js
window.WebToApk.clearSharedText()
```

Clears the kept share once the page has consumed it.

**Example**

Forgets the text or link that was shared into the app, once your page has used it.

**Returns:** nothing. **Needs:** nothing (the share itself needs **Receive Shares From Other Apps** with **Text and links** ticked).

Read the kept share, use it, then clear it so it is not handled again after a reload:

```js
if (window.WebToApk && typeof window.WebToApk.getSharedText === 'function') {
  var raw = window.WebToApk.getSharedText();
  if (raw) {
    var shared = JSON.parse(raw);          // { text, subject, url, receivedAt }
    saveNote(shared.subject, shared.text);
    window.WebToApk.clearSharedText();     // getSharedText() now returns ""
  }
}

window.addEventListener('appmint:shared', function (e) {
  saveNote(e.detail.subject, e.detail.text);
  if (window.WebToApk && window.WebToApk.clearSharedText) window.WebToApk.clearSharedText();
});
```

**Notes:** Clearing only affects `getSharedText()`. A new share replaces the kept one and fires `appmint:shared` again. Files shared into the app are released separately with `AppMint.releaseOpenedFile()`.

### `copyToClipboard`

```js
window.WebToApk.copyToClipboard(text: String): Boolean
```

The Android share sheet, the system clipboard, and closing a window the page opened. These are the plain-web equivalents (navigator.share, navigator.clipboard, window.close) answered natively so they behave the same inside the app.

_Described by its group, Share, clipboard and window, rather than on its own._

**Example**

Copies plain text to the phone's clipboard. Pages normally use the standard `navigator.clipboard.writeText(text)`, which the shell routes here.

**Returns:** `true` on success, `false` on failure (synchronously). **Needs:** nothing.

The standard API first:

```js
document.getElementById('copy-btn').onclick = async function () {
  try {
    await navigator.clipboard.writeText('PROMO-2026');
    showMessage('Copied');
  } catch (e) {
    showMessage('Could not copy');
  }
};
```

The raw call:

```js
if (window.WebToApk && typeof window.WebToApk.copyToClipboard === 'function') {
  var ok = window.WebToApk.copyToClipboard('PROMO-2026');
  showMessage(ok ? 'Copied' : 'Could not copy');
}
```

**Notes:** Plain text only (no images or HTML). Android 13+ shows its own small "Copied" preview, so you may not need your own message there.

### `getSharedText`

```js
window.WebToApk.getSharedText(): String
```

Text or a link another app shared INTO this one ("Share to <app>" - a YouTube video shared from the YouTube app arrives as its link), as JSON `{text, subject, url, receivedAt}` or "" when nothing was shared. Kept until read, so an app that mounts after the share still sees it; a share arriving while the app runs also fires `appmint:shared`. A photo or video shared with a caption delivers the file through AppMint.getOpenedFile() and the caption here. Requires the build's "Receive shares from other apps" option with "Text and links" ticked, which registers the share-sheet entry.

**Example**

Text or a link that another app shared INTO your app ("Share → your app"), as a JSON string, or `""` when nothing was shared.

**Returns:** a JSON string `{text, subject, url, receivedAt}` or `""` (synchronously). `url` is the first `http(s)://` link found in `text` (or `""`); `receivedAt` is a time in milliseconds. **Needs:** **Receive Shares From Other Apps** switched on when you build, with **Text and links** ticked - that puts your app in other apps' Share menu.

The share is kept until you clear it, so read it on start, and listen for shares that arrive while the app runs:

```js
function handleShare(s) {
  addBookmark(s.url || s.text, s.subject);
  if (window.WebToApk && window.WebToApk.clearSharedText) window.WebToApk.clearSharedText();
}

// 1. On start (the app may have been opened by the share).
if (window.WebToApk && typeof window.WebToApk.getSharedText === 'function') {
  var raw = window.WebToApk.getSharedText();
  if (raw) handleShare(JSON.parse(raw));
}

// 2. While running: detail has the same keys { text, subject, url, receivedAt }.
window.addEventListener('appmint:shared', function (e) {
  handleShare(e.detail);
});
```

A global hook receives the same object, if you prefer one:

```js
window.onAppMintShared = function (s) { handleShare(s); };
```

**Notes:** A YouTube video shared from the YouTube app arrives as its link. A photo or video shared WITH a caption delivers the file through `AppMint.getOpenedFile()` and the caption here. Clear the share after you use it, or you will see it again on the next start. AI-built apps can use `sharedText()` / `onShared()` from `@/lib/appmintNative`.

### `print`

```js
window.WebToApk.print()
```

Hands the page as it currently stands to Android's print dialogue, which can print on paper or save a PDF. Nothing to configure - the WebView renders the document.

_Described by its group, Printing, rather than on its own._

**Example**

Opens Android's print screen for the page as it looks now - print on paper or "Save as PDF". Pages normally use the standard `window.print()`, which the shell routes here.

**Returns:** nothing. **Needs:** nothing.

The standard API first:

```js
document.getElementById('print-btn').onclick = function () {
  window.print();   // in the app: the Android print screen
};
```

The raw call does the same:

```js
if (window.WebToApk && typeof window.WebToApk.print === 'function') {
  window.WebToApk.print();
}
```

**Notes:** It prints the whole WebView - the main page. A same-origin iframe's own `print()` prints just that iframe (see `window.print`). Use a `@media print` stylesheet to hide buttons and menus. The job is named "<App name> Document". Errors are only logged.

### `readClipboard`

```js
window.WebToApk.readClipboard(): String
```

The Android share sheet, the system clipboard, and closing a window the page opened. These are the plain-web equivalents (navigator.share, navigator.clipboard, window.close) answered natively so they behave the same inside the app.

_Described by its group, Share, clipboard and window, rather than on its own._

**Example**

Reads the text that is on the phone's clipboard now. Pages normally use the standard `navigator.clipboard.readText()`, which the shell routes here.

**Returns:** the text, or `""` when the clipboard is empty or cannot be read (synchronously). **Needs:** nothing.

The standard API first - for example a "Paste code" button:

```js
document.getElementById('paste-btn').onclick = async function () {
  try {
    var text = await navigator.clipboard.readText();
    if (text) document.getElementById('code').value = text.trim();
    else showMessage('The clipboard is empty');
  } catch (e) {
    showMessage('Could not read the clipboard');
  }
};
```

The raw call:

```js
if (window.WebToApk && typeof window.WebToApk.readClipboard === 'function') {
  var text = window.WebToApk.readClipboard();
  if (text) document.getElementById('code').value = text;
}
```

**Notes:** Only your own app's pages can read it: a foreign website opened inside the app gets `""`. Android only lets the app read the clipboard while it is on screen, and Android 12+ shows a "pasted from clipboard" notice - read it on a user tap, not on page load.

### `shareFiles`

```js
window.WebToApk.shareFiles(filesJson: String, title: String, text: String): Boolean
```

TRUE native file share for navigator.share({files:[...]}). Android WebView has no Web Share API, and text/plain ACTION_SEND can't carry a file - so before this a shared image was merely SAVED, not shared. filesJson is [{name, mimeType, base64}, ...]; we write each to cache, expose it via the app's FileProvider, and fire ACTION_SEND / ACTION_SEND_MULTIPLE so the real Android share sheet (WhatsApp, Gmail, …) opens. Returns true if the sheet opened.

**Example**

Shares one or more real files (an image, a PDF…) through the Android share sheet. Pages normally use the standard `navigator.share({ files: [...] })`, which the shell routes here.

**Returns:** `true` if the share sheet opened, `false` otherwise (synchronously). **Needs:** nothing.

The standard API first:

```js
async function shareCanvas(canvas) {
  var blob = await new Promise(function (r) { canvas.toBlob(r, 'image/png'); });
  var file = new File([blob], 'drawing.png', { type: 'image/png' });
  if (!(navigator.canShare && navigator.canShare({ files: [file] }))) {
    alert('File sharing is not available here');
    return;
  }
  try {
    await navigator.share({ files: [file], title: 'My drawing', text: 'Made in my app' });
  } catch (e) { /* in a browser: the user closed the sheet */ }
}
```

The raw call takes a JSON string of `[{name, mimeType, base64}]` (base64 without the `data:` prefix), then `title` and `text`:

```js
function shareBase64Png(base64) {
  if (!(window.WebToApk && typeof window.WebToApk.shareFiles === 'function')) return false;
  var files = [{ name: 'receipt.png', mimeType: 'image/png', base64: base64 }];
  return window.WebToApk.shareFiles(JSON.stringify(files), 'Receipt', 'Your receipt');
}
```

**Notes:** Files are written to the app's cache and shared through its FileProvider. Unsafe characters in `name` become `_`. Several files of one type share with that type; mixed types share as `*/*`. The whole file travels as base64 over the bridge, so keep it to a few MB. When `navigator.share({files})` cannot open the sheet, the shell saves the files as downloads instead and the promise still resolves.

### `shareNative`

```js
window.WebToApk.shareNative(title: String, text: String, url: String)
```

The Android share sheet, the system clipboard, and closing a window the page opened. These are the plain-web equivalents (navigator.share, navigator.clipboard, window.close) answered natively so they behave the same inside the app.

_Described by its group, Share, clipboard and window, rather than on its own._

**Example**

Opens the Android share sheet with a title, text and link. Pages normally use the standard `navigator.share({title, text, url})`, which the shell routes here.

**Returns:** nothing (it cannot tell you which app the user picked). **Needs:** nothing.

The standard API first - it also works in a mobile browser:

```js
document.getElementById('share-btn').onclick = async function () {
  if (!navigator.share) { alert('Sharing is not available here'); return; }
  try {
    await navigator.share({ title: 'My app', text: 'Look at this', url: 'https://mysite.com/item/42' });
  } catch (e) {
    // in a browser: AbortError when the user closes the sheet
  }
};
```

The raw call, all three arguments are strings (use `''` to leave one out):

```js
if (window.WebToApk && typeof window.WebToApk.shareNative === 'function') {
  window.WebToApk.shareNative('My app', 'Look at this', 'https://mysite.com/item/42');
}
```

**Notes:** The shared text is `text` + a new line + `url` (or just one of them). `title` becomes the email subject and the share sheet's heading. Text and links only - to share a file, use `navigator.share({files})` (see `shareFiles`).

