MessageEvent
La interface MessageEvent
representa un mensaje recibido por un objeto de destino.
Este es usado para representar mensajes en :
- Eventos enviados por el servidor(ver
EventSource.onmessage
(en-US)). - Web sockets (ver la propiedad
onmessage
de la interface WebSocket ). - Mensajeria cruzada(ver
Window.postMessage()
(en-US) yWindow.onmessage
). - Mensajes de canal (en-US)(ver
MessagePort.postMessage()
(en-US) yMessagePort.onmessage
(en-US)). - Trabajo cruzado / Mensajes de texto (vea las dos entradas anteriores, pero también
Worker.postMessage()
(en-US),Worker.onmessage
(en-US),ServiceWorkerGlobalScope.onmessage
(en-US), etc.) - Canales de Transmisión (en-US)(ver
Broadcastchannel.postMessage()
(en-US)) yBroadcastChannel.onmessage
(en-US)). - Canal de datos WebRTC (ver
RTCDataChannel.onmessage
(en-US)).
La acción desencadenada por este evento es definida en una función establecida como el controlador de eventos para el evento pertinente message
( es decir : Usando un manejador de onmessage
como se lista arriba).
Nota: Esta característica está disponible en Web Workers
Constructor
MessageEvent()
(en-US)-
Crear un nuevo
MessageEvent
.
Propiedades
Esta interface tambien herada propiedadesde desde su padre Evento
.
MessageEvent.data
(en-US) Read only-
La información enviada por el emisor del mensaje.
MessageEvent.origin
(en-US) Read only-
USVString
(en-US) es una representacion del origen del emisor del mensaje. MessageEvent.lastEventId
(en-US) Read only-
DOMString
es una representación de una ID unico para el evento. MessageEvent.source
(en-US) Read only-
El
MessageEventSource
(El cual puede ser unWindowProxy
,MessagePort
(en-US), orServiceWorker
(en-US) object) es ima representación del mensaje emitido. MessageEvent.ports
(en-US) Read only-
Un array de objetos
MessagePort
(en-US) representa los puertos asociados al canal, el mensaje se esta enviado a traves de (donde sea apropiado, por ejemplo, en mensajes de canal o al enviar un mensaje a un trabajador compartido).
Metodos
Esta interface tambien herada propiedadesde desde su padre, Evento
.
MessageEvent.initMessageEvent()
Deprecated-
Inicializar un vento de mensaje. No use esto mas — en vez de eso use el constructor
MessageEvent()
(en-US) .
Ejemplos
En nuestro Ejemplo basico de trabajador compartido(Ejecutar trabajador compartdo), Tenemos dos paginas HTML, cada una de las cuales usa algo de JavaScript para mejorar un calculo simple. Los diferentes scripts estan usando el mismo archivo de trabajo para mejorar el calculo — Ambos pueden accederlo, Incluso si sus paginas esta corriendo n diferentes ventanas.
The following code snippet shows creation of a SharedWorker
object using the SharedWorker()
(en-US) constructor. Both scripts contain this:
var myWorker = new SharedWorker('worker.js');
Both scripts then access the worker through a MessagePort
(en-US) object created using the SharedWorker.port
(en-US) property. If the onmessage event is attached using addEventListener, the port is manually started using its start()
method:
myWorker.port.start();
When the port is started, both scripts post messages to the worker and handle messages sent from it using port.postMessage()
and port.onmessage
, respectively:
first.onchange = function() {
myWorker.port.postMessage([first.value,second.value]);
console.log('Message posted to worker');
}
second.onchange = function() {
myWorker.port.postMessage([first.value,second.value]);
console.log('Message posted to worker');
}
myWorker.port.onmessage = function(e) {
result1.textContent = e.data;
console.log('Message received from worker');
}
Inside the worker we use the SharedWorkerGlobalScope.onconnect
(en-US) handler to connect to the same port discussed above. The ports associated with that worker are accessible in the connect
event's ports
property — we then use MessagePort
(en-US) start()
method to start the port, and the onmessage
handler to deal with messages sent from the main threads.
onconnect = function(e) {
var port = e.ports[0];
port.addEventListener('message', function(e) {
var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
port.postMessage(workerResult);
});
port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
}
Especificaciones
Specification |
---|
HTML Standard # the-messageevent-interface |
Compatibilidad entre navegadores
BCD tables only load in the browser
Ver tambien
ExtendableMessageEvent
(en-US) — similar to this interface but used in interfaces that needs to give more flexibility to authors.