Reputation: 31
I'm developing a Chrome app, and I need to get the external IP address.
I've tried loading external scripts, but I was getting errors even though I added the sources to 'content_security_policy'
on the manifest.json
file.
I gave up, and then I tried making an XMLHttpRequest
request to an IP host/service website, but requests need to be async and I wasn't able to save the response to a variable even using setTimeout()
.
I was always getting undefined
because the variable was clearly being set before the request was completed.
So can you please help me find a simple solution to get the IP?
Upvotes: 3
Views: 1447
Reputation: 69346
This site http://jsonip.com/ outputs a JSON
object like this:
{"ip":"xxx.xxx.xxx.xxx","about":"/about","Pro!":"http://getjsonip.com"}
You can perform an asynchronous XMLHttpRequest
to that site like this:
var xhr = new XMLHttpRequest(),
IP_ADDRESS;
xhr.onreadystatechange = function() {
if (xhr.readyState==4 && xhr.status==200) {
IP_ADDRESS = JSON.parse(xhr.responseText).ip;
console.log('IP ADDRESS: ' + IP_ADDRESS);
// Log it or do something else so you'll know that the response has been received
}
}
xhr.open('GET', 'http://jsonip.com/', true);
xhr.send();
After a while you'll see a log like this in the console:
IP ADDRESS: 12.34.567.89
Upvotes: 3