aframeaframe-networked

Text messaging using a-frame


I want to add a text chat system in a-frame. I'm using networked a-frame as connectivity can be anything possible with that or I've to do using some other tech.


Solution

  • There is a simple API to send custom messages with the network layer that is already setup:

    // subscribe to custom data
    NAF.connection.subscribeToDataChannel(dataType, (senderId, dataType, data, targetId) => {})
    
    // send custom data
    NAF.connection.broadcastData(dataType, data)
    

    So sending an chat message is as simple as:

    const btn = document.querySelector("button");      // SEND btn
    const input = document.querySelector("input");     // input field with the text
    const log = document.querySelector("#messages")    // message log
    
    // when you want to send a message
    btn.addEventListener("click", evt => {
      // log your own messages
      messages.innerHTML += NAF.clientId + ": " + input.value + '<br>'
      // broadcast the text as some unique dataType (like "chat")
      NAF.connection.broadcastData("chat", {txt: input.value}) 
    })
    
    // when a "chat" type message arrives
    NAF.connection.subscribeToDataChannel("chat", (senderId, dataType, data, targetId) => {
      // append the data.txt to the message log
      messages.innerHTML += senderId + ": " + data.txt + '<br>'
    })
    

    Check it out in this glitch:

    enter image description here