Reputation: 814
I have 2 separate pages, each opens a web socket to the server, one pages fires a message to the server, is there any way that the other page can receive the reply? Any help is greatly appreciated.
Thanks
First Page, connects and waits for message
<html>
<head>
<script type="text/javascript" charset="utf-8">
if("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:12345/server.php");
}
function startSocket() {
if("WebSocket" in window) {
ws.onopen = function (event) {
document.getElementById('status').innerHTML = "open: " + this.readyState;
}
ws.onmessage = function (message) {
alert(message.data);
}
}
}
</script>
</head>
<body onLoad="startSocket()">
<div id="status">
</div>
<div id="stock">
</div>
</body>
</html>
Second Page sends message to server via web scoket
<html>
<script type="text/javascript" charset="utf-8">
if("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:12345/server.php");
}
function startSocket() {
if("WebSocket" in window) {
ws.onopen = function (event) {
document.getElementById('status').innerHTML = "open: " + this.readyState;
}
}
}
function send() {
var text = "hello";
try {
ws.send(text);
} catch (exception) {
alert(exception.Description);
}
}
</script>
<body onLoad="startSocket()">
<div id="status"></div>
<div id="stock"></div>
<button onClick="send();">Left!</button>
</body>
</html>
Upvotes: 1
Views: 2554
Reputation: 3448
If the second page is created by the first and given a name and both are on the same domain, you can access scripts in the second page by using its name.
its exactly the same as passing information from an iframe to its containing webpage. security prevents this working if the two pages are in different domains as that would be the target of XSS attacks.
DC
In your example there is no communication between the pages. from your comment I see you are trying to implement a chat system. So NO they cannot talk to each other.
Sorry I thought both pages were hosted in the same browser.
when you connect to server.php you are not connecting to the same script twice you are connecting to two independant copies of the same script. so unless you do some work in server php to get the message and return it then no message will be passed back
Also by default server.php will disconnect after 30 seconds. so you need to disable that.
What you are trying to do is MUCH more complicated than you seem to realise
DC
Upvotes: 2