Presentation

In controlling the browsing context, the Presentation interface provides a mechanism to override the browser default behaviour of launching presentation to an external screen.


const presentationRequest = new PresentationRequest(['receiver/index.html']);
navigator.presentation.defaultRequest = presentationRequest;
let presentationConnection;

presentationRequest.start()
.then(connection => { // ...})
.catch(error => { /* ... */});

presentationRequest.addEventListener('connectionavailable', function(event) {
  presentationConnection = event.connection;
  presentationConnection.addEventListener('close', function() {});
  presentationConnection.addEventListener('terminate', function() {});
  presentationConnection.addEventListener('message',  function(event) {});
});

//......
presentationConnection.send('a string');
//......
presentationConnection.close();
//......
presentationConnection.terminate();
//......
presentationRequest.reconnect(presentationId)
.then(connection => {
    console.log('Reconnected to ' + connection.id);
}).catch(error => { /* ... */});
//......
presentationRequest.getAvailability().then(availability => {
   console.log('Available presentation displays: ' + availability.value);
   availability.addEventListener('change', function() {
      console.log('> Available presentation displays: ' + availability.value);
   });
}).catch(error => { /* ... */ });

In receiving the browsing context, the Presentation interface provides access to the available presentation connections.


let connectionIdx = 0;
let messageIdx = 0;

function addConnection(connection) {
   connection.connectionId = ++connectionIdx;
   addMessage('New connection #' + connectionIdx);
   connection.addEventListener('message', function(event) {
      messageIdx++;
      const data = JSON.parse(event.data);const logString = 'Message ' + messageIdx + ' from connection #' + connection.connectionId + ': ' + data.message;
      addMessage(logString, data.lang);
      maybeSetFruit(data.message);
      connection.send('Received message ' + messageIdx);
   });
   connection.addEventListener('close', function(event) {
      addMessage('Connection #' + connection.connectionId + ' closed, reason = ' + event.reason + ', message = ' + event.message);
   });
};

document.addEventListener('DOMContentLoaded', function() {
   if (navigator.presentation.receiver) {
      navigator.presentation.receiver.connectionList.then(list => {
         list.connections.map(connection => addConnection(connection));
         list.addEventListener('connectionavailable', event => {
            addConnection(event.connection);
         });
      });
   }
});
// ......

This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.