---
title: Ascoltare in una pagina web
project: OpenSync
version: 1.0
section: recipes
language: it
license: MIT
url: https://totaljs.es/docs/it/opensync/1-0/recipes/web-page/
updated: 2026-11-19T09:22:09.965Z
---

# Ascoltare in una pagina web

> Mostra i messaggi in tempo reale in una pagina web con il WebSocket del browser.

Una pagina web può connettersi a OpenSync con il `WebSocket` del browser, anche quando la pagina si trova su un altro indirizzo. Usa un token limitato ai canali che servono alla pagina: chiunque apra la pagina può leggere il token nel suo codice sorgente.

## La pagina

```html
<!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<title>Live orders</title>
</head>
<body>
	<ul id="orders"></ul>
	<script>
		var ws = new WebSocket('wss://sync.example.com/?token=YOUR_TOKEN&app=Browser');
		ws.onmessage = function(e) {
			var msg = JSON.parse(e.data);
			if (msg.channel !== 'orders')
				return;
			var li = document.createElement('li');
			li.textContent = msg.method + ' ' + JSON.stringify(msg.body);
			document.getElementById('orders').appendChild(li);
		};
	</script>
</body>
</html>
```

Il messaggio `init` non ha `channel`, quindi la pagina lo salta.

## Inviare dalla pagina

La pagina può anche inviare a un canale tramite la stessa connessione:

```js
ws.send(JSON.stringify({ type: 'notify', channel: 'chat', body: { text: 'Hi' } }));
```

## Perché non EventSource o fetch?

OpenSync non invia header CORS. Per questo un browser blocca uno stream `EventSource`, e un `fetch` JSON verso `/sync/`, da una pagina su un altro indirizzo. WebSocket non ne è toccato. Invia invece i dati a `/sync/` dal tuo server.
