How to get client IP address in JavaScript? - javascript

I'm trying to get the client's IP address. This is my code so far.
Any suggestions?
<script type="application/javascript">
function getIP(json) {
document.write("My public IP address is: ", json.ip);
}
</script>
<script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=getIP"></script>

Try This.Little bit Help to you.
<script type="application/javascript">
function getIP(json) {
document.write("My public IP address is: ", json.ip);
}
</script>
<script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=getIP"></script>

please try below code:-
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
Ip Address:=<h3 class='ipAdd'><h3>
</body>
<script>
$(document).ready(function ubsrt()
{
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new RTCPeerConnection({iceServers:[]}),
noop = function(){};
pc.createDataChannel("");
pc.createOffer(pc.setLocalDescription.bind(pc), noop);
pc.onicecandidate = function(ice){
if(!ice || !ice.candidate || !ice.candidate.candidate) return;
var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
$('.ipAdd').text(myIP);
pc.onicecandidate = noop;
};
});
</script>
</html>

function user_location() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log( this.responseText);
}
};
xhttp.open("GET", "//api.ipify.org?format=json", true);
xhttp.send();
}

The JSON variable that is returned can be navigated like any object in javascript.
<textarea id="text" style="width:100%;height:120px;"></textarea>
<script type="application/javascript">
function getIP(json) {
document.getElementById("text").value = JSON.stringify(json, null, 2);
for (key in json) {
document.write("<br>" + key + " : ", json[key]);
}
}
</script>
<script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=getIP"></script>

try this
$.ajax({
url: "//api.ipify.org/?format=json",
dataType: 'JSON',
}).success(function(data) {
console.log(data.ip);
}).error(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});

How to get current ip address using angular?
Please refer link : https://github.com/apilayer/freegeoip#readme
https://ipstack.com/
OR
getIpAddress(){
this.http.get<{ip:string}>('https://jsonip.com')
.subscribe( data => {
console.log('th data', data);
this.ipAddress = data
})
}

<script>
$.getJSON('http://ip-api.com/json', function(ipData){
document.write(ipData.query)
});
</script>

Related

How to detect visitor country using simple Javascript

This code is not working on squarespace, can someone identify whats wrong with this code. However, its working on jsfiddle.
<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script>
jQuery(document).ready(function($) {
jQuery.getScript('http://www.geoplugin.net/javascript.gp', function()
{
var country = geoplugin_countryName();
alert(country);
var code = geoplugin_countryCode();
alert(code);
console.log("Your location is: " + country + ", " + zone + ", " + district);
});
});</script>
I have added the code for region and city which was missing, try this it works now,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script>
jQuery(document).ready(function($) {
jQuery.getScript('http://www.geoplugin.net/javascript.gp', function()
{
const country = geoplugin_countryName();
const countryCode = geoplugin_countryCode();
const city = geoplugin_city();
const region = geoplugin_region();
console.log(`Your location is: ${city}, ${region}, ${country}, ${countryCode}`);
alert(`Your location is: ${city}, ${region}, ${country}, ${countryCode}`)
});
});
Update:-
As the above plugin was hosted over HTTP and was giving error, this is the alternate solution to it,
fetch('https://extreme-ip-lookup.com/json/')
.then(res => res.json())
.then(res => {
console.log(res);
document.getElementById('target').innerHTML = `Your location is: ${res.city}, ${res.region}, ${res.country}`;
})
.catch((data, status) => {
console.log('Request failed');
})
The variables "zone" and "district" are not defined, remove them and it will work, use this:
<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<script>
jQuery(document).ready(function ($) {
jQuery.getScript('http://www.geoplugin.net/javascript.gp', function () {
var country = geoplugin_countryName();
alert(country);
var code = geoplugin_countryCode();
alert(code);
console.log("Your location is: " + country);
});
});
</script>

How to get google plus user image?

I tried to search on stackoverflow but all answer not work.
This is my code for get google plus user image, but not work.
How can i do that ?
<html>
<head>
<script src="https://apis.google.com/js/plusone.js"></script>
<script type="text/javascript">
function onSignin(e){
accessToken = e.access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://www.googleapis.com/plus/v1/people/me/");
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.send();
xhr.onreadystatechange = function(){
if (this.readyState == 4){
var myProfile = JSON.parse(xhr.responseText);
alert(myProfile.image.url);
}
}
}
</script>
</head>
<body>
<g:plus action="connect" clientid="100009709084787102522" scope="https://www.googleapis.com/auth/plus.me" callback="onSignin">
</g:plus>
</body>
</html>

When I Replace Remote File with Local File Console Error - Skulpt

I am making a Python editor in HTML and JavaScript, with CodeMirror for code indentation, line numbering and syntax coloring, and Skulpt for the execution.
I have some code that had an external script referenced in it (http://www.skulpt.org/static/skulpt.min.js):
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript">
</script>
<script src="http://www.skulpt.org/static/skulpt.min.js" type="text/javascript">
</script>
<script src="skulpt-stdlib.js" type="text/javascript">
</script>
<script src="codemirror.js" type="text/javascript">
</script>
<script src="python.js" type="text/javascript">
</script>
<link href="codemirror.css" rel="stylesheet" type="text/css">
<title></title>
</head>
<body>
<script type="text/javascript">
var editor;
function outf(text) {
var mypre = document.getElementById("dynamicframe");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
}
function runit() {
var prog = editor.getDoc().getValue();
var mypre = document.getElementById("dynamicframe");
mypre.innerHTML = '';
Sk.pre = "dynamicframe";
Sk.configure({
output: outf,
read: builtinRead
});
(Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'canvas';
var myPromise = Sk.misceval.asyncToPromise(function() {
return Sk.importMainWithBody("<stdin>", false, prog, true);
});
myPromise.then(function(mod) {
console.log('success');
},
function(err) {
console.log(err.toString());
});
}
//<![CDATA[
window.onload = function() {
editor = CodeMirror.fromTextArea(document.getElementById('textbox'), {
mode: {
name: "python",
version: 2,
singleLineStringErrors: false
},
lineNumbers: true,
indentUnit: 4
});
} //]]>
</script>
<textarea id="textbox" name="textbox"></textarea>
<br>
<button onclick="runit()" type="button">Run</button>
<pre id="dynamicframe"></pre>
<div id="canvas"></div>
</body>
</html>
I want all the scripts stored locally (excluding jQuery), so I copied over http://www.skulpt.org/static/skulpt.min.js to the local server and called it skulpt.min.js. I then changed the line:
<script src="http://www.skulpt.org/static/skulpt.min.js" type="text/javascript">
</script>
to...
<script src="skulpt.min.js" type="text/javascript">
</script>
and now the code is bringing up this error in the console:
Uncaught ReferenceError: Sk is not defined
on line 38 of the HTML:
Sk.pre = "dynamicframe";
Why is this happening and how can I fix it?

how to talk to cleverbot via input box?

i recently found a script that uses cleverbot's api. i'm able to get a response when i enter a variable in the ask() function, but how can i make it so that a user can communicate with cleverbot by entering a value in an input box?
also, cleverbot's api only prints responses into the console.log() so i had to use the code at the bottom to transcribe the entries into the .console div:
$(document).ready(function() {
var bot = new cleverbot("BIsKhtIhZdmgbOPp", "DwikyXztHk6GEG7LcvHCKfObCxYduTMP");
bot.setNick("sessionname")
bot.create(function (err, session) {
// session is your session name, it will either be as you set it previously, or cleverbot.io will generate one for you
// Woo, you initialized cleverbot.io. Insert further code here
});
$('#clever').keyup(function (e) {
if (e.keyCode == 13) {
var value = $(this).val();
var input = value;
if (value == input) {
document.getElementById("input").innerHTML =
'<p>> ' + bot.ask(input, function (err, response) {
console.log(input);
console.log(response);
}); + '</p>';
}
}
});
if (typeof console != "undefined")
if (typeof console.log != 'undefined')
console.olog = console.log;
else
console.olog = function() {};
console.log = function(message) {
console.olog(message);
$('.console').append('<br>' + '<p>> ' + message + '</p>');
};
console.error = console.debug = console.info = console.log
});
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro:400,700,300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://unilogue.github.io/css/style.css">
<script type="text/javascript" src="https://unilogue.github.io/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://unilogue.github.io/js/cleverbot/cleverbot.io.js"></script>
</head>
<body>
<div class="console" style="width:75%;"></div>
<div id="input"></div>
<p>> </p><input id="clever" type="text" placeholder="say something clever." />
</body>
</html>
i updated the snippet and added an if... statement to enable dialogue.
$(document).ready(function() {
var bot = new cleverbot("BIsKhtIhZdmgbOPp", "DwikyXztHk6GEG7LcvHCKfObCxYduTMP");
bot.setNick("sessionname")
bot.create(function (err, session) {
// session is your session name, it will either be as you set it previously, or cleverbot.io will generate one for you
// Woo, you initialized cleverbot.io. Insert further code here
});
$('#clever').keyup(function (e) {
if (e.keyCode == 13) {
var value = $(this).val();
var input = value;
if (value == input) {
document.getElementById("input").innerHTML =
bot.ask(input, function (err, response) {
console.log('me > ' + input);
console.log('cb > ' + response); // Will likely be: "Living in a lonely world"
});
$(this).val('');
}
}
});
$('html').keydown(function(e) {
if (e.which == 118) {
window.open('/', '_self');
}
});
if (typeof console != "undefined")
if (typeof console.log != 'undefined')
console.olog = console.log;
else
console.olog = function() {};
console.log = function(message) {
console.olog(message);
$('.console').append('<br>' + '<p>' + message + '</p>');
};
console.error = console.debug = console.info = console.log
});
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro:400,700,300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://unilogue.github.io/css/style.css">
<script type="text/javascript" src="https://unilogue.github.io/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://unilogue.github.io/js/cleverbot/cleverbot.io.js"></script>
</head>
<body>
<div class="console"><div id="input" style="display:none;"></div></div>
<p>me > </p><input id="clever" type="text" placeholder="say something clever." spellcheck="false" />
</body>
</html>

FusionTables private table with OAUTH2

Good pic by Tim Rosenberg that shows exactly how OAUTH2 work's:
I'm kind a lazy to even start looking on this 2 files and test
so I searched for easyest way to
1.get token
2.access with that token
with help of gwt-oauth2
put it into index.php head :
<script type="text/javascript" src="gwt-oauth2.js"></script>
and this in body
<script type="text/javascript">
(function() {
var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
var GOOGLE_CLIENT_ID = "CLIENT_ID";
//var PLUS_ME_SCOPE = "https://www.googleapis.com/auth/plus.me";
//var FusionTable_SCOPE = "https://www.googleapis.com/auth/fusiontables";
var button = document.createElement("button");
button.innerText = "Authenticate with Google";
button.onclick = function() {
var req = {
'authUrl' : GOOGLE_AUTH_URL,
'clientId' : GOOGLE_CLIENT_ID,
'scopes': ['https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/fusiontables'
],
};
oauth2.login(req, function(token) {
alert('Got an OAuth token:\n'+ token +'\n'+ 'Token expires in '+ oauth2.expiresIn(req) +' ms\n');
}, function(error) {
alert("Error:\n" + error);
});
};
var dv = document.getElementById('admin-content');
dv.appendChild(button);
var clearTokens = document.createElement('button');
clearTokens.innerText = 'Clear all tokens'
clearTokens.onclick = oauth2.clearAllTokens;
dv.appendChild(clearTokens);
})();
</script>
OK,
Now you can see connection and redirection to oauthWindow.html in new window without errors. GET parameters now showing you access_token token_type expires_in. Check the access_token HERE
As you see access_token working great BUT
What you still don't get is first alert from that :
oauth2.login(req, function(token) {
alert('Got an OAuth token:\n' + token + '\n'
+ 'Token expires in ' + oauth2.expiresIn(req) + ' ms\n');
}, function(error) {
alert("Error:\n" + error);
});
Second alert works fine and when you try to Auth. again if oauthWindow.html still open it shows you an error alert(so it's working!)
Now let's add that little code to oauthWindow.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (window.opener && window.opener.oauth2 && window.opener.oauth2.__doLogin) {
window.opener.oauth2.__doLogin(location.hash);
} else {
document.body.innerText = "Your browser seems to be stopping this window from communicating with the main window.";
}
</script>
</head>
<body></body>
</html>
Perfect!
Now if you want to work with private tables all you need is to add an access_token to url.
Thanks for giving me the reason to answer myself!
Put this into oauthWindow.html file
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (window.opener && window.opener.oauth2 && window.opener.oauth2.__doLogin) {
window.opener.oauth2.__doLogin(location.hash);
} else {
document.body.innerText = "Your browser seems to be stopping this window from communicating with the main window.";
}
</script>
</head>
<body></body>
</html>

Categories