DEV Community

Matthew Cullen
Matthew Cullen

Posted on

Tracking a user's IP address through a hidden form field

The script will make a call to an api that returns the clients IP address and then sets the hidden form field to the returned value.

<!DOCTYPE html>
<html>
  <head>
    ...
  </head>
  <body>
    <form name="contact"  action="/form_submission_page.html">
      <input type="text" id="ipFormInput" hidden>
      <input type="submit" value="Send">
    </form>
  </body>

  <script type="application/javascript ">
    const ipFormInput = document.getElementById('ipFormInput');

    fetch('https://api.ipify.org?format=json')
        .then((response) => { return response.json() })
        .then((json) => {
            const ip = json.ip;
            ipFormInput.value = ip;
            console.log(ip);
        })
        .catch((err) => { console.error(`Error getting IP Address: ${err}`) })
  </script>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
deleteduser profile image
Deleted User

This works fine, but only for PC users.
Is it possible to make it work for mobile as well?

Collapse
 
deleteduser profile image
Deleted User

Further testing: The code works on mobile users as well, but only for FireFox is malfunctioning.

Is there something that can be done in order to work for FireFox mobile users as well?

Collapse
 
deleteduser profile image
Deleted User

Further testing: The code is also malfunctioning for Safari and probably Apple users in general.