websockethttpscross-domainmixed-content

How to make a HTTP request to a LocalNetwork from a HTTPS WebSite?


let's assume that there is a website under HTTPS, in that WebSite the user can set the IP of a local machine (thermal printer in this case). How can the user print something on that printer by using the website from his device?

The user have to use the WebSite only under the local network where the thermal printer is to be able to print.

The printer has a http server in it which it uses for the communication.

At this point how can a HTTPS website send a HTTP request to that local thermal printer?


Solution

  • Assuming you want this to be a variable that any user inputs,and that any user on any network has the ability to access their own printer, you would need it to be executed on the frontend. This way each user will be able to access the printer on their own network.

    That gives you basically one option. Javascript. So if you wanted a stored request with some variables, you could have the javascript store variable from the DOM and then post a fetch request https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch Here is an example function

    // Example POST method implementation:
    async function postData(url = '', data = {}) {
      // Default options are marked with *
      const response = await fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify(data) // body data type must match "Content-Type" header
      });
      return response.json(); // parses JSON response into native JavaScript objects
    }
    
    postData('https://example.com/answer', { answer: 42 })
      .then(data => {
        console.log(data); // JSON data parsed by `data.json()` call
      });
    

    You are likely struggling because of CORS. You can find in depth discussion here https://javascript.info/fetch-crossorigin

    In short, you will need to modify the fetch headers to have the correct credentials, mode, etc. as seen in the comments in the above snippet.