Reputation: 11
I want to communicate between two different HTML files. One is opened on my iPad (iPad.html) and the other one on my pc (pc.html). When I press a button on the iPad.html I want to execute a function on the pc.html.
Is this possible with HTML and Javscript only? There would be a solution with PHP but I want to keep it "simple".
Upvotes: 1
Views: 712
Reputation: 13
Yes, you can achieve this using WebSockets for real-time communication. Here's a simple setup:
Set up a WebSocket server (e.g., with Node.js and ws
library):
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (socket) => {
socket.on('message', (message) => {
server.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) client.send(message);
});
});
});
iPad.html:
<button onclick="sendMessage()">Send to PC</button>
<script>
const ws = new WebSocket('ws://<YOUR_SERVER_IP>:8080');
function sendMessage() {
ws.send('Button pressed on iPad');
}
</script>
pc.html:
<p id="display">Waiting...</p>
<script>
const ws = new WebSocket('ws://<YOUR_SERVER_IP>:8080');
ws.onmessage = (event) => {
document.getElementById('display').textContent = event.data;
};
</script>
Open iPad.html on the iPad and pc.html on the PC. When the button is pressed, the message will display on the PC.
Upvotes: 0
Reputation: 499
one solution to achive this is by using websockets. Which holds a continuous connection with the server.
The flow will be like this.
Please take a look on this php websockets library http://socketo.me/docs/hello-world
Since you are using only html there should be an broker to pass information from one client to another. So you have program some server side code otherwise it is difficult to achieve it.
Upvotes: 1
Reputation: 486
I don't think this is possible, because they don't know each other, yet. You can change that if you modify one of the clients to interact as a server, but if you say that you only want to use Javascript, take a look at Node.js, Node lets you build a server backend with pure javascript, then you can connect both clients to this node server and can communicate over that.
Upvotes: 0