0

I'm trying the example from ipify to obtain a client IP:

<script type="application/javascript">
  function getIP(json) {
    document.write("My public IP address is: ", json.ip);
  }
</script>

<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>

This works fine.

When I try to add this into my document, nothing appears:

JS

<script type="application/javascript">
var s$ = function(e) {return document.getElementById(e);};

function getIP(json) {
    s$('clientIP').innerHTML = json.ip;
}
</script>

<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>

HTML

<div>
    <p><label for="clientIP">clientIP</label><span id="clientIP"></span></p>
</div>

Looking at the Chrome console, this error appears:

Failed to load resource: net::ERR_BLOCKED_BY_CLIENT

Not sure I understand why the first method works, the second does not.

<div>
  <p><label for="clientIP">clientIP</label><span id="clientIP"></span></p>
</div>
<script type="application/javascript">
  var s$ = function(e) {
    return document.getElementById(e);
  };

  function getIP(json) {
    s$('clientIP').innerHTML = json.ip;
  }
</script>

<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>

Running this incognito, I get the following error:

Uncaught TypeError: Cannot set property 'innerHTML' of null
    at getIP (VM26:10)
    at api.ipify.org/:1

Full HTML

Kermit
  • 32,563
  • 10
  • 80
  • 117

1 Answers1

1

This is most like happening because of an ad blocker plugin (such as AdBlock plus). To test this, try running in incognito mode, or try running it in another browser.

To permanently fix it, you can remove the ad blocker extension.

I can't be sure of the exact algorithm that the ad blocker is using, but something in your second snippet is triggering the ad blocker to "think" that it needs to block that content.

Regarding your second question (cannot set property of null), that is most likely because the element you are attempting to reference ('clientIP'), has not been rendered yet. This is where something like jQuery comes in very handy, as you can leverage the document.ready event. This ensures that your code fires after the DOM has completed rendering. The way you have it now (in your second snippet), the DOM isn't guaranteed to be rendered when your code executes. Without jQuery, you can utilize a timeout, however, and do something like this:

<script type="application/javascript">
var s$ = function(e) {return document.getElementById(e);};

function getIP(json) {
    setTimeout(function() {
        s$('clientIP').innerHTML = json.ip;
    }, 1000);
}
</script>
Matt Spinks
  • 5,382
  • 1
  • 18
  • 39