Hi I want to check response times of website. Here is my code, I got some values but doesn't show reality. What is the problem with these codes. Is it sth related with cache?? Furthermore how to show if page doesn't exit or unavailable.
<script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript">
var start = new Date();
$.ajax ({
url: 'http://www.example.com',
complete : function()
{
alert(new Date() - start)
},
});
</script>
The code itself is fine assuming that the code is running on the same origin as the one it's checking; you can't use ajax cross-origin unless both ends (client and server) support and are using CORS.
It could be caching, yes, you'd have to refer to the browser tools (any decent browser has a Network tab or similar in its developer tools) to know for sure. You can also disable caching by setting cache: false in the ajax call (see the ajax documentation for details), although that's a somewhat synthetic way to do it. A better way would be to ensure that whatever URL you're using for this timing responds with cache headers telling the browser (and proxies) not to cache it.
You can tell if the page doesn't exist or is "unavailable" (whatever that means) by hooking the error function and looking at the information it gives you:
var start = new Date();
$.ajax ({
url: 'http://www.example.com',
error : function(jqxhr, status, ex) {
// Look at status here
},
complete : function()
{
alert(new Date() - start)
},
});
The arguments given to error are also described in the docs linked above.
You can't do this due to the same origin policy.
One trick would be to create an image and measure the time until the onerror event fires.
var start = new Date();
var img = new Image();
img.onerror = function() {
alert(new Date() - start);
};
img.src = 'http://www.example.com/';
Append a random number to the url to prevent caching.
I'd use browser extensions such as Firebug or Chrome Developer Tools to measure Ajax response times.
Related
I have a JQuery ajax request that can return error status and messages.
To handle them I use this code :
$.ajax("url", {
options: options
}).done(function(text, statusText, data) {
//Manage data
}).fail(function(data) {
//Manage fail
});
In the fail handle I want, in case of 500: internal server error, to open a new tab with the response text (for debug purposes)
I do it this way :
if (data.status === 500) {
var w = window.open("App error", "blank");
w.document.write(data.responseText);
}
And it works !
Except one point : my browser loads the page, the content is displayed (and as it's static content all of this is not a real problem), but the tab is marked as loading... Loading... Loading...
I'm using Firefox 63.0(64bits).
Does anyone know where this comes from ? It's not really annoying, it's just a (fun ?) behavior I don't understand.
Here is a fiddle on which I get the exact same behavior.
It has to do with the w.document.write line. If you close the document, the loader will finish. Change the code to:
if (data.status === 500) {
var w = window.open("App error", "blank");
w.document.write(data.responseText);
w.document.close();
}
Source: Open about:blank window in firefox
The problem is that you are opening a tab without an url, and most browsers expect an url, that's what I do in order to get rid of it:
const newWindow = window.open('#');
if (newWindow) {
newWindow.addEventListener('load', () => {
newWindow.document.open();
newWindow.document.write(request.responseText);
newWindow.document.close();
newWindow.stop();
}, true);
You can replace # with any url path that doesn't exist, the important thing is that once it's loaded, you'll be able to override the content.
It's not the best solution but at least it makes the trick
I'm coding a script in nodejs to automatically retrieve data from an online directory.
Knowing that I had never done this, I chose javascript because it is a language I use every day.
I therefore from the few tips I could find on google use request with cheerios to easily access components of dom of the page.
I found and retrieved all the necessary information, the only missing step is to recover the link to the next page except that the one is generated 4 seconds after loading of page and link contains a hash so that this step Is unavoidable.
What I would like to do is to recover dom of page 4-5 seconds after its loading to be able to recover the link
I looked on the internet, and much advice to use PhantomJS for this manipulation, but I can not get it to work after many attempts with node.
This is my code :
#!/usr/bin/env node
require('babel-register');
import request from 'request'
import cheerio from 'cheerio'
import phantom from 'node-phantom'
phantom.create(function(err,ph) {
return ph.createPage(function(err,page) {
return page.open(url, function(err,status) {
console.log("opened site? ", status);
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function(err) {
//jQuery Loaded.
//Wait for a bit for AJAX content to load on the page. Here, we are waiting 5 seconds.
setTimeout(function() {
return page.evaluate(function() {
var tt = cheerio.load($this.html())
console.log(tt)
}, function(err,result) {
console.log(result);
ph.exit();
});
}, 5000);
});
});
});
});
but i get this error :
return ph.createPage(function (page) {
^
TypeError: ph.createPage is not a function
Is what I am about to do is the best way to do what I want to do? If not what is the simplest way? If so, where does my error come from?
If You dont have to use phantomjs You can use nightmare to do it.
It is pretty neat library to solve problems like yours, it uses electron as web browser and You can run it with or without showing window (You can also open developer tools like in Google Chrome)
It has only one flaw if You want to run it on server without graphical interface that You must install at least framebuffer.
Nightmare has method like wait(cssSelector) that will wait until some element appears on website.
Your code would be something like:
const Nightmare = require('nightmare');
const nightmare = Nightmare({
show: true, // will show browser window
openDevTools: true // will open dev tools in browser window
});
const url = 'http://hakier.pl';
const selector = '#someElementSelectorWitchWillAppearAfterSomeDelay';
nightmare
.goto(url)
.wait(selector)
.evaluate(selector => {
return {
nextPage: document.querySelector(selector).getAttribute('href')
};
}, selector)
.then(extracted => {
console.log(extracted.nextPage); //Your extracted data from evaluate
});
//this variable will be injected into evaluate callback
//it is required to inject required variables like this,
// because You have different - browser scope inside this
// callback and You will not has access to node.js variables not injected
Happy hacking!
I need to extend firebug to use the link extracted from the webpage(when a download from any link in the page is initiated) to send it to another machine where it will be downloaded. I was planning to use firebug to extract this link for me. If there is any other way I can get this information from the browser, even that would be appreciated.
Typo in above answer observer service call should read: Components.classes["#mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService);
Reference for Observer Service usage: https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIObserverService
actually, its bad idea to use events to detect things like http requests,the power of firefox xul language gives you the ability to detect the all browsers requests/response then you can decide what links you need from the request/response header:
you can use "http-observe" witch actually Firebug use for the net panel
- here is the link for "http-observe" in mozilla MDN [https://developer.mozilla.org/en/Setting_HTTP_request_headers][1]
- also here is a simple example for "http-observe"
// first create observerService component as a property into your extension javascript object
var myExtension = { observerService:Components.classes["#mozilla.org/observerservice;1"].getService(Components.interfaces.nsIObserverService),
init:function(){
// in the init function setup the observe service and set witch javascript object is the listener for http response for example "this"
this.observerService.addObserver(this,"http-on-examine-response", false);
this.observerService.addObserver(this,"http-on-examine-cached-response", false);
},
observe: function(aSubject, aTopic, aData){ // the observe function
if (aTopic == "http-on-examine-response" || aTopic == "http-on-examine-cached-response"){
var httpChannel = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
var URI = httpChannel.originalURI.spec;
if (aSubject.loadFlags & httpChannel.LOAD_INITIAL_DOCUMENT_URI){ // this detect if the response is primery request
var contentType = httpChannel.getResponseHeader("content-type"); // check the heder content-type
if (contentType == "what ever you want"){ // you can check if it zip/html/xml ...etc
//do what ever you want
}
}
}
}
}
I have a basic html page which has links that point to different site. What I want to do is track the clicks. I am doing so by sending a 0 pixel image call on Click event of the link without returning false on click event.
The same works fine on all the browsers except Safari(on windows OS).
when a link is clicked using javascript I delay the redirect and send an image request over to the server and log the click on server side. I have tried increasing the delay but with no success... The trackers work gr8 on all the browsers except Safari which does not sent the request at all.
I dont know why but possibly its that safari waits for the complete js to be executed before making the request and after the whole js is executed it gets redirected....
=========================================================
<html>
<head>
<script type="text/javascript">
function logEvent(){
image = new Image(1,1);
image.onLoad=function(){alert("Loaded");};
image.onLoad=function(){alert("Error");};
image.src='http://#path_to_logger_php#/log.php?'+Math.random(0, 1000) + '=' + Math.random(0, 1000);
pauseRedirect(500);
}
function pauseRedirect(millis){
var date = new Date();
var curDate = null;
do {curDate = new Date();}
while(curDate-date < millis);
}
</script>
</head>
<body>
Site 1<br/>
Site 2<br/>
</body>
</html>
=========================================================
Code works in chrome, firefox, ie and Opera. Does not work on Safari only..... any clues....
I had the same issue with all WebKit browsers. In all others you only need to do new Image().src = "url", and the browser will send the request even when navigating to a new page. WebKit will stop the request before it's sent when you navigate to a new page right after. Tried several hacks that inject the image to the document and even force a re-paint through img.clientHeight. I really don't want to use event.preventDefault, since that causes a lot of headaches when a link has target="_blank", form submit, etc. Ended up using a synchronous XmlHttpRequest for browsers supporting Cross Origin Resource Sharing, since it will send the request to the server even though you don't get to read the response. A synchronous request has the unfortunate side-effect of locking the UI-thread while waiting for response, so if the server is slow the page/browser will lock up until it receives a response.
var supportsCrossOriginResourceSharing = (typeof XMLHttpRequest != "undefined" && "withCredentials" in new XMLHttpRequest());
function logEvent() {
var trackUrl = 'http://#path_to_logger_php#/log.php?'+Math.random(0, 1000) + '=' + Math.random(0, 1000);
if(supportsCrossOriginResourceSharing) {
xhrTrack(trackUrl);
} else {
imgTrack(trackUrl);
}
}
function xhrTrack(trackUrl) {
var xhr = new XMLHttpRequest();
xhr.open("GET", trackUrl, false);
xhr.onreadystatechange = function() {
if(xhr.readyState >= this.OPENED) xhr.abort();
}
try { xhr.send() } catch(e) {}
}
function imgTrack(trackUrl) {
var trackImg = new Image(1,1);
trackImg.src = trackUrl;
}
I'm working on an application that allows the user to send a file using a form (a POST request), and that executes a series of GET requests while that file is being uploaded to gather information about the state of the upload.
It works fine in IE and Firefox, but not so much in Chrome and Safari.
The problem is that even though send() is called on the XMLHttpRequest object, nothing is being requested as can be seen in Fiddler.
To be more specific, an event handler is placed on the "submit" event of the form, that places a timeout function call on the window:
window.setTimeout(startPolling, 10);
and in this function "startPolling" sequence is started that keeps firing GET requests to receive status updates from a web service that returns text/json that can be used to update the UI.
Is this a limitation (perhaps security-wise?) on WebKit based browsers? Is this a Chrome bug? (I'm seeing the same behaviour in Safari though).
I am having the exact same problem. At the moment i use an iframe, which is targeted in the form. That allows the xhr requests to be executed while posting. While that does work, it doesn't degrade gracefully if someone disables javascript.(I couldn't load the next page outside the iframe without js) So if someone has a nicer solution, i would be grateful to hear it.
Here the jQuery script for reference:
$(function() {
$('form[enctype=multipart/form-data]').submit(function(){
// Prevent multiple submits
if ($.data(this, 'submitted')) return false;
var freq = 500; // freqency of update in ms
var progress_url = '{% url checker_progress %}'; // ajax view serving progress info
$("#progressbar").progressbar({
value: 0
});
$("#progress").overlay({
top: 272,
api: true,
closeOnClick: false,
closeOnEsc: false,
expose: {
color: '#333',
loadSpeed: 1000,
opacity: 0.9
},
}).load();
// Update progress bar
function update_progress_info() {
$.getJSON(progress_url, {}, function(data, status){
if (data) {
var progresse = parseInt(data.progress);
$('#progressbar div').animate({width: progresse + '%' },{ queue:'false', duration:500, easing:"swing" });
}
window.setTimeout(update_progress_info, freq);
});
};
window.setTimeout(update_progress_info, freq);
$.data(this, 'submitted', true); // mark form as submitted.
});
});