Search code examples
javascriptmessage

Passing message between two html pages using javascript


I have two HTML pages: source.html and dest.html

  • In source.html, I create some buttons (start, stop, pause ...)
  • In dest.html, I create a simple clock.

Whenever I click on one of these buttons, the source will send a message to dest. After being processed, the result (based on which button was pressed) will be sent back to the source. I tried iframe, but it did not work for me. Are there any suggestions that do not use the client-server model?


Solution

  • There are 2 ways to send the message.

    1. In source create a form which submits to dest.html, make sure the method is 'GET'

    2. On click of the button set the value of the message and submit the form

      // something like document.getElementById('message').value = 'HELLO'; document.getElementById('form').submit();

    2a. You dont need to make the form, you can just redirect with hardcoded url on the source.html button click like

    window.location = 'dest.html?message=somemessage';
    
    1. On submit the dest.html file will open, with the message available in the URL of the page

      var url = window.location+"";

      // if there are multiple parameters you will have to loop and store them in array for single you can use

      var message = url.substr((url.indexOf('=')+1)); alert(message);

    2nd Method Not tried, store them in cookies when button gets clicked on source.html and read the cookies in dest.html