Search code examples
javascripthtmlelementtransfer

Is there anyway to transfer html elements from one client to another with keeping of every entered values like in textboxes?


Let's say I have a page with some html elements. Those elements are textboxes ,checkboxes ,radiobuttons and other user responsive things.

I need a possibility to transfer whole page from client1 to client2, so client2 will see everything that client1 has set into html elements.

I use WebSocket technology for that, but I don't know how to transfer that elements. If I transfer document.body.innerHTML then client2 see blank elements, instead of filled ones. enter image description here

On the page could be any amount of any html elements. Is it possible to do something like clonning elements but over websocket? Like I serialize whole document.body and transfer it to another client?

The page are simple html ones. No any server side script are used. I use self made http + websocket server that is working on same port.


Solution

  • You need to use outerHTML instead of innerHTML, however that wont set your input values so you have to do that manually.

    // To send your html via websocket
    //var ws = new WebSocket('ws://my.url.com:PORT');
    //ws.onopen = function(event) { // Make sure it only runs after the web socket is open
    
      document.querySelector('button').addEventListener("click", function() {
        var inputs = document.querySelectorAll('input');
        Array.prototype.forEach.call(inputs, function(el, i) {
          el.setAttribute('value', el.value);
        });
        document.querySelector('button').setAttribute('data-button', true); // Attributes are rememebered
        var HTML = document.querySelector('section').outerHTML;
        document.querySelector('#result').innerHTML = HTML;
        document.querySelector('#resulttext').textContent = HTML;
    
        //ws.send(HTML);
      });
    
    //};
    html,
    body {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
    }
    div {
      background: orange;
      border: 3px solid black;
    }
    <section>
      <div>
        <input />
      </div>
      <div>
        <input />
      </div>
      <div>
        <input />
      </div>
      <div>
        <input />
      </div>
      <div>
        <input />
      </div>
      <div>
        <button>Generate</button>
      </div>
    </section>
    <p id="resulttext"></p>
    <p id="result"></p>