-1

So I made this IP script were when you get on my website it shows you your IP.

What I want to do is make a simple IP blocker, I want it to find the value of the header that contains the IP address as text, and make it so that if IPHEADER.text or something == "GOODIP" alert("RIGHT IP!"); else window.location = "SOMETHING" ... I know that was bad JavaScript, but it was just an example.

Here is the current code I have.

<h3 id="testIp"></h3>

<script>
  function text(url) {
    return fetch(url).then(res => res.text());
  }

  text('https://www.cloudflare.com/cdn-cgi/trace').then(data => {
    let ipRegex = /[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/
    let ip = data.match(ipRegex)[0];
    document.getElementById('testIp').innerHTML = (ip);
  });
-->NEED HELP PAST HERE<---
  function validate() {
    if (document.getElementById("testIp").innerHTML == "The Right IP") {
      alert("RIGHT IP!");
    } else {
      alert('WRONG IP!');
    }
  }

</script>

Thanks!

user9384
  • 27
  • 10
  • 2
    Why don't you try `.textContent` rather than `.innerHTML` if you want to compare raw text? – Mr. Polywhirl Mar 15 '21 at 14:29
  • I am not getting any errors on my code, its just that its not working. – user9384 Mar 15 '21 at 14:30
  • 1
    Put the `if ...` part into the `then` callback. Timing-wise it's only guaranteed that the value is available there. Or pass the value via parameter: `function validate(ip) ...`, and call it from within the `.then`: `validate(ip)`. – deceze Mar 15 '21 at 14:32
  • This does not answer, nor does it work with my code. Sorry – user9384 Mar 15 '21 at 14:39

1 Answers1

1

There are a couple things you could change to correct your code.

  1. Escape the dot-literals in your regular expression (\.)
  2. Use .textContent to extract only the raw text from the <h3>.
  3. When comparing two text strings, always use triple-equals (===)

const
  PATTERN_IP_ADDRESS = /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/,
  blockedIpAddress   = '127.0.0.1';

const fetchText = url => fetch(url).then(res => res.text());

const validate = () => {
  const testIp = document.getElementById('testIp');
  const ipAddress = testIp.textContent;

  if (ipAddress === blockedIpAddress) {
    console.log('RIGHT IP!');
  } else {
    console.log('WRONG IP!');
    testIp.classList.add('wrong');
  }
}

fetchText('https://www.cloudflare.com/cdn-cgi/trace').then(text => {
  const [ ip ] = text.match(PATTERN_IP_ADDRESS);
  document.getElementById('testIp').innerHTML = ip;
  validate();
});
.wrong { color: red; }
<h3 id="testIp"></h3>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • 1
    Thank you so much, now I can make an IP blocker without using PHP or .htaccess! ... not sure why this has negative rep but whatever. – user9384 Mar 15 '21 at 14:49