Home > Software engineering >  How to Print *console.log* IP address
How to Print *console.log* IP address

Time:05-18

I have a piece of JS code which uses a public API by ipify to access my/or clients' IP address. I was essentially wondering if I could somehow print the json.ip (IP address) to the console)? It seems fairly obvious but I can't make it work.

  <script type="application/javascript">
  function getIP(json) {
    dataLayer.push({"event":"ipEvent","ipAddress" : json.ip});  
  }
</script>

<script type="ap.....

CodePudding user response:

<!DOCTYPE html>
<html>

<head>
    <title>Getting Clients IP</title>
    <style>
    p,
    h1 {
        color: green;
    }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
    <script>
    /* Add "https://api.ipify.org?format=json" statement
            this will communicate with the ipify servers in
            order to retrieve the IP address $.getJSON will
            load JSON-encoded data from the server using a
            GET HTTP request */

    $.getJSON("https://api.ipify.org?format=json", function(data) {

        // Setting text of element P with id gfg
        $("#gfg").html(data.ip);
    })
    </script>
</head>

<body>
    <center>
        <h1>IP address!</h1>
        <h3>Public IP Address of user is:</h3>
        <p id="gfg"></p>
    </center>
</body>

</html>

CodePudding user response:

I guess you could just use jsonp and have it callback to the console on load.

<script src="https://api.ipify.org?format=jsonp&callback=console.log"></script>

Or if you just want to type the command into the browser console you could use:

fetch("https://api.ipify.org").then(p => p.text()).then(p => console.log(p))

Run the snippet to try

<script src="https://api.ipify.org?format=jsonp&callback=console.log"></script>

  • Related