Conexiune sockets intre 2 pagini web

Am 2 pagini HTML/JavaScript in October CMS (Laravel). Cand sunt pe pagina 1 si apas pe un buton, vreau ca pagina 2 sa afiseze o informatie. Problema e ca nu resuesc deloc sa fac socket-ul sa functioneze…

Aveti o idee/exemplu de cod cat mai simplu? Primesc eroarea urmatoare: Firefox can’t establish a connection to the server at ws://myproject.test/index (myproject.test/index fiind pagina 2).

Pagina 1:

let socket = new WebSocket("ws://myproject.test/index");

		socket.onopen = function(e) {
		  socket.send("My name is Johnss");
		};

		socket.onmessage = function(event) {
		  alert(`[message] Data received from server: ${event.data}`);
		};

		socket.onerror = function(error) {
		  console.log(error);
		};

Am tot catuat solutii, dar degeaba… Am incercat pe Google Chrome, la fel…

Nu ma pricep, dar cred ca ai nevoie si de un server.

Este vorba despre 2 pagini diferite din același site deschise in acelasi browser (taburi, windowuri diferite)? Daca da, atunci poti sa folosesti Broadcast Channel.

1 Like

Nu e clar ce vrei sa faci.

De ce ai decis ca ai nevoie de websockets ? De ce pagini vorbim ?

Websockets se foloseste pentru a trimite date bidirectional in timp real. Ai nevoie de un server. Apăsarea unui buton si afișarea datelor pe o pagina in timp real se poate rezolva cu server-side events.

Oricum ai nevoie de un server, asta dacă nu vorbim de tab-uri diferite.

Dacă vorbim de mai multe tab-uri deschise și vrei să se poată comunica între ele, poți folosi BroadcastChannel (așa cum ți-a spus deja micku7zu). Aici găsești documentația: BroadcastChannel - Web APIs | MDN

Uite și exemplu. Creează două fișiere, deschide-le în ferestre separate și apasă butonul într-una din ele.

tab-1.html

<!DOCTYPE html>
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
	<button>Send message to channel</button>
	
	<script>
		/* Channel */
		ThisIsMyChannel = new BroadcastChannel('talk_with_other_tabs');
		
		/* Button click event */
		document.querySelector('button').addEventListener('click', function(){
			/* Send message using the channel */
			ThisIsMyChannel.postMessage({
				message: 'Message sent from tab 1'
			});
		})
		
		/* Catch channel messages */
		ThisIsMyChannel.addEventListener('message', function(event){
			document.title = event.data.message;
		})
	</script>
</body>
</html>

tab-2.html

<!DOCTYPE html>
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
	<button>Send message to channel</button>
	
	<script>
		/* Channel */
		ThisIsMyChannel = new BroadcastChannel('talk_with_other_tabs');
		
		/* Button click event */
		document.querySelector('button').addEventListener('click', function(){
			/* Send message using the channel */
			ThisIsMyChannel.postMessage({
				message: 'Message sent from tab 2'
			});
		})
		
		/* Catch channel messages */
		ThisIsMyChannel.addEventListener('message', function(event){
			document.title = event.data.message;
		})
	</script>
</body>
</html>

În cod, singura diferență e mesajul trimis (Message sent from tab xxx).

Dacă intenționezi să folosești una din pagini ca iframe (widget, de exemplu), atunci ai putea folosi:

index.html

<!DOCTYPE html>
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
	<iframe src="iframe.html" style="display:block; width:500px; height:300px; border:1px solid red"></iframe>

	<button>Send message to iframe</button>
	
	<script>
		/* Message number */
		messageNumber = 1;
		
		/* Catch button click */
		document.querySelector('button').addEventListener('click', function(){
			/* Send message to iframe */
			document.querySelector('iframe').contentWindow.postMessage({
				message: 'Message number ' + messageNumber + ' sent by index.html!'
			});
			
			/* Increment message number */
			messageNumber++;
		})
	</script>
</body>
</html>

iframe.html

<!DOCTYPE html>
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
	<p>I'm a frame (iframe)</p>
	
	<script>
		/* Catch messages from parent (you should check from message origin) */
		onmessage = function(event){
			document.body.insertAdjacentHTML(
				'beforeend',
				'<p><b>' + event.data.message + '</b></p>'
			);
		}
	</script>
</body>
</html>