I am building a so called random art generator using the HTML5 canvas element. Now I want the buttons that control the visual action on the canvas in realtime to be in a separate window. Is there a way to do that? I suppose I need one javascript controlling two separate browser windows.
2 Answers 2
You can use cross-document messaging provided that your two pages are from the same origin (protocol, hostname, port). This is how it is done:
On your page that should send information (that with your buttons) you invoke this:
window.postMessage(message, origin);
which will send the message provided to the origin given (the url of your other page).
On your receving page you include this function:
window.addEventListener("message", yourfunction);
where yourfunction takes an argument, e. e is of the type MessageEvent and contains the following properties:
- data
- origin
- source (Returns the window associated with the sending script.)
And that's all there is to it!
1 Comment
You need communication API for Cross Document Messaging.
You can use postMessage to send and receive messages.
//Post message
window.postMessage('Hello world...', 'http://example.com');
//Bind events
window.addEventListener('message', messageHandler, true);
Also don't forget to check browser support:
if(typeof window.postMessage === "undefined"){
alert('Your browser doesnt support this functionality');
}