I have an IP Camera that streams out live video to a web site of mine. Problem is, it is powered by an ActiveX control. Even worse, this control is unsigned. To provide a more secure alternative to the people that are using browsers other than IE, or are (rightfully) unwilling to change their security settings, I am tapping into the cameras built in snap-shot script that serves up a 640x480 live JPEG image. The plan was to update the image live on the screen every ~500ms using Javascript without having to reload the entire page.
I tried using the Image() object to pre-load the image and update the SRC attribute of the image element when onload fired:
function updateCam() {
var url = "../snapshot.cgi?t=" + new Date().getTime();
img = new Image();
img.onload = function() {
$("#livePhoto").attr("src", url);
camTimer = setTimeout(updateCam, 500);
}
img.src = url;
}
This worked decently, but it was difficult to determine when the camera had been disabled, which I needed to do in order to degrade gracefully. The internal snapshot script is setup to return an HTTP status code of 204 (No Content) under this circumstance, and of course there is no way for me to detect that using the Image object. Additionally, the onload event was not 100% reliable.
Therefore, I am using the jQuery (version 1.2.6) ajax function to do a GET request on the URL, and on the complete callback I evaluate the status code and set the URL accordingly:
function updateCam() {
var url = "../snapshot.cgi?t=" + new Date().getTime();
$.ajax({
type: "GET",
url: url,
timeout: 2000,
complete: function(xhr) {
try {
var src = (xhr.status == 200) ? url : '../i/cam-oos.jpg';
$("#livePhoto").attr("src", src);
}
catch(e) {
JoshError.log(e);
}
camTimer = setTimeout(updateCam, 500);
}
});
}
And this works beautifully. But only in IE! This is the question that I would like to have answered: Why doesn't this work in Firefox or Chrome? The complete event does not even fire in Firefox. It does fire in Chrome, but only very rarely does setting the SRC actually load the image that was requested (usually it displays nothing).
Posting a second answer, because the first was just really incorrect. I can't test this solution (because I don't have access to your webcam script), but I would suggest trying to sanitise the response from the camera - since you obviously can't handle the raw image data, try adding the dataFilter setting like so:
function updateCam() {
var url = "../snapshopt.cgi?t=" + new Date().getTime();
$.ajax({
type: "GET",
url: url,
timeout: 2000,
dataFilter : function(data, type) {
return '<div></div>' //so it returns something...
},
complete: function(xhr) {
try {
var src = (xhr.status == 200) ? url : '../i/cam-oos.jpg';
$("#live").attr("src", src);
}
catch(e) {
JoshError.log(e);
}
camTimer = setTimeout(updateCam, 500);
}
});
}
Like I said, I haven't been able to test this - but it might allow jquery to use the status codes without breaking like crazy.
img.onerror = function(){
alert('offline');
}
Well, I ended up using the data URI scheme (hat tip to Eric Pascarello) for non-IE browsers. I wrote a HTTP handler (in VB.NET) to proxy the IP camera and base-64 encode the image:
Imports Common
Imports System.IO
Imports System.Net
Public Class LiveCam
Implements IHttpHandler
Private ReadOnly URL As String = "http://12.34.56.78/snapshot.cgi"
Private ReadOnly FAIL As String = Common.MapPath("~/i/cam-oos.jpg")
Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
Dim Data As Byte()
With context.Response
.ContentEncoding = Encoding.UTF8
.ContentType = "text/plain"
.Write("data:image/png;base64,")
Try
Using Client As New WebClient()
Data = Client.DownloadData(URL)
End Using
Catch ex As WebException
Data = File.ReadAllBytes(FAIL)
End Try
.Write(Convert.ToBase64String(Data))
End With
End Sub
End Class
Then I just put a little non-IE detection (using the classic document.all check) in order to call the correct URL/set the correct SRC:
function updateCam() {
var url = (document.all) ? "../snapshot.cgi?t=" : "../cam.axd?t=";
url += new Date().getTime();
$.ajax({
type: "GET",
url: url,
timeout: 2000,
complete: function(xhr) {
try {
var src;
if(document.all)
src = (xhr.status == 200) ? url : '../i/cam-oos.jpg';
else
src = xhr.responseText;
$("#livePhoto").attr("src", src);
}
catch(e) {
JoshError.log(e);
}
camTimer = setTimeout(updateCam, 500);
}
});
}
It's very unfortunate I had to resort to this workaround for. I hate browser detection code, and I hate the additional load that is put on my server. The proxy will not only force me to waste more bandwidth, but it will not operate as efficiently because of the inherent proxy drawbacks and due to the time required to base-64 encode the image. Additionally, it is not setup to degrade as gracefully as IE. Although I could re-write the proxy to use HttpWebRequest and return the proper status codes, etc. I just wanted the easiest way out as possible because I am sick of dealing with this!
Thanks to all!
I believe the jquery will try to interpret the response from the server. I believe some browsers are more tolerant of the response interpretation so more restrictive browsers will fail because an image cannot be seen as HTML!
The solution to this would be to use a HEAD request type instead of a GET ( type: "HEAD" ). That way you will still get status responses back, without grabbing the image itself. Therefore the response will be empty (and shouldn't mess you up). Also, the response should be much faster.
Related
I am using ajax to connect to a view in my web application.
$.ajax({
url: url,
type: 'PATCH',
success: function() {
var d = new Date();
img = e.target.parentElement.parentElement.getElementsByTagName('img')[0];
if (img.src.includes("?")){
img.src = img.src.split("?")[0] + '?' + d.getTime();
} else {
img.src = img.src + '?' + d.getTime();
}
},
});
When I click on the button that triggers this, everything works, but I get an XML Parsing error. According to the other questions on stack exchange, this might be beacuse of an empty content. When I use the firefox developer tools, the content of the reverse of the concerned view is indeed empty, because of which, I think, firefox interprets it as an xml.
My problem is, that I do not know how to fill the content. In my view, I changed return Response(status=200) to return Response(status=200, content_type='image/jpeg'), because the view does something to an image. But still the content seems to stay empty and I still get the error. I don't know how else to alter the content type than by specifying it in the response.
I only get this error in firefox, not in chrome.
Turns out I only had to set the content_type to text/html...
The server response is missing header Content-Type.
So the JavaScript 'success' handler cannot parse correctly the response body.
I have a html page using javascript that gives the user the option to read and use his own text files from his PC. But I want to have an example file on the server that the user can open via a click on a button.
I have no idea what is the best way to open a server file. I googled a bit. (I'm new to html and javascript, so maybe my understanding of the following is incorrect!). I found that javascript is client based and it is not very straightforward to open a server file. It looks like it is easiest to use an iframe (?).
So I'm trying (first test is simply to open it onload of the webpage) the following. With kgr.bss on the same directory on the server as my html page:
<IFRAME SRC="kgr.bss" ID="myframe" onLoad="readFile();"> </IFRAME>
and (with file_inhoud, lines defined elsewhere)
function readFile() {
func="readFile=";
debug2("0");
var x=document.getElementById("myframe");
debug2("1");
var doc = x.contentDocument ? x.contentDocument : (x.contentWindow.document || x.document);
debug2("1a"+doc);
var file_inhoud=doc.document.body;
debug2("2:");
lines = file_inhoud.split("\n");
debug2("3");
fileloaded();
debug2("4");
}
Debug function shows:
readFile=0//readFile=1//readFile=1a[object HTMLDocument]//
So statement that stops the program is:
var file_inhoud=doc.document.body;
What is wrong? What is correct (or best) way to read this file?
Note: I see that the file is read and displayed in the frame.
Thanks!
Your best bet, since the file is on your server is to retrieve it via "ajax". This stands for Asynchronous JavaScript And XML, but the XML part is completely optional, it can be used with all sorts of content types (including plain text). (For that matter, the asynchronous part is optional as well, but it's best to stick with that.)
Here's a basic example of requesting text file data using ajax:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
You'd call that like this:
getFileFromServer("path/to/file", function(text) {
if (text === null) {
// An error occurred
}
else {
// `text` is the file text
}
});
However, the above is somewhat simplified. It would work with modern browsers, but not some older ones, where you have to work around some issues.
Update: You said in a comment below that you're using jQuery. If so, you can use its ajax function and get the benefit of jQuery's workarounds for some browser inconsistencies:
$.ajax({
type: "GET",
url: "path/to/file",
success: function(text) {
// `text` is the file text
},
error: function() {
// An error occurred
}
});
Side note:
I found that javascript is client based...
No. This is a myth. JavaScript is just a programming language. It can be used in browsers, on servers, on your workstation, etc. In fact, JavaScript was originally developed for server-side use.
These days, the most common use (and your use-case) is indeed in web browsers, client-side, but JavaScript is not limited to the client in the general case. And it's having a major resurgence on the server and elsewhere, in fact.
The usual way to retrieve a text file (or any other server side resource) is to use AJAX. Here is an example of how you could alert the contents of a text file:
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){alert(xhr.responseText);};
xhr.open("GET","kgr.bss"); //assuming kgr.bss is plaintext
xhr.send();
The problem with your ultimate goal however is that it has traditionally not been possible to use javascript to access the client file system. However, the new HTML5 file API is changing this. You can read up on it here.
I would like to poll an anchor's href source about once every 5 seconds, to see whether a file at that address is present. When it is present, display an image in the anchor. In other words, the link is basically not there unless the file is present.
I'm guessing I would have to poll using an http HEAD request to determine whether the file exists, then toggle the image appropriately. Once the file has been determined to exist, I can stop polling and leave the image visible.
Is there a better way to do this, and can anyone suggest some script that would handle this functionality?
If your server is configured to do so you can use:
http://api.jquery.com/jQuery.ajax/
To poll for the file's existence by using the statusCode map
function checkFile() {
$.ajax({
statusCode: {
404: function() {
//file does not yet exist
setTimeout(checkFile, 5000);
}
200: function() {
//file exists.
showImage();
}
}
});
}
You may want to capture a few more edge cases though, (for example, an error callback).
// note, this piece of code assumes to be using jQuery
var interval = setInterval(function(){
var _el=$('#hrefId');
var href = _el.attr('href');
if(href == null || typeof href == 'undefined' || href == '')
return;
ajax call to href(in case on ur server(!) )
// on success
_el.attr('href','TheLink');
$('img', _el).show(); // show image
}, 5);
You can also use a socket library so the server can push a notification when the image is ready. socket.io seems like a good options here.
Another way would be to listen for the error event on the image, then wait for x milliseconds before trying to load it again. This is quite easy to implement, because every time you define a src attribute, the browser will add new listeners.
It’s basically the same as your meta-description but you don’t need to use ajax. You will also be able to load images from other domains (ajax have a cross-site policy):
var img = new Image(),
src = '/path/to/image.jpg';
img.onload = function() {
console.log('loaded', img);
};
img.onerror = function() {
window.setTimeout(function() {
img.src = src;
},500);
};
img.src = src;
Here is a proof of concept: http://jsfiddle.net/L2L3U/. The program will try to load a 404 image for three seconds, after that I change the src to a real image and it will display it.
Out of curiosity, I'm wondering about the best (easiest, fastest, shortest, etc; make your pick) way to perform a GET request in JavaScript without using AJAX or any external libraries.
It must work cross-browser and it's not allowed to distort the hosting web page visually or affect it's functionality in any way.
I don't care about headers in the request, just the url-part. I also don't care about the result of the request. I just want the server to do something as a side effect when it receives this request, so firing it is all that matters. If your solution requires the servers to return something in particular, that's ok as well.
I'll post my own suggestion as a possible answer, but I would love it if someone could find a better way!
Have you tried using an Image object? Something like:
var req = new Image();
req.onload = function() {
// Probably not required if you're only interested in
// making the request and don't need a callback function
}
req.src = 'http://example.com/foo/bar';
function GET(url) {
var head = document.getElementsByTagName('head')[0];
var n = document.createElement('script');
n.src = url;
n.type = 'text/javascript';
n.onload = function() { // this is not really mandatory, but removes the tag when finished.
head.removeChild(n);
};
head.appendChild(n);
}
I would go with Pekka idea and use hidden iframe, the advantage is that no further parsing will be done: for image, the browser will try to parse the result as image, for dynamically creating script tag the browser will try to parse the results as JavaScript code.. iframe is "hit and run", the browser doesn't care what's in there.
Changing your own solution a bit:
function GET(url) {
var oFrame = document.getElementById("MyAjaxFrame");
if (!oFrame) {
oFrame = document.createElement("iframe");
oFrame.style.display = "none";
oFrame.id = "MyAjaxFrame";
document.body.appendChild(oFrame);
}
oFrame.src = url;
}
Short version question :
Is there navigator.mozIsLocallyAvailable equivalent function that works on all browsers, or an alternative?
Long version :)
Hi,
Here is my situation :
I want to implement an HtmlHelper extension for asp.net MVC that handle image post-loading easily (using jQuery).
So i render the page with empty image sources with the source specified in the "alt" attribute.
I insert image sources after the "window.onload" event, and it works great.
I did something like this :
$(window).bind('load', function() {
var plImages = $(".postLoad");
plImages.each(function() {
$(this).attr("src", $(this).attr("alt"));
});
});
The problem is : After the first loading, post-loaded images are cached. But if the page takes 10 seconds to load, the cached post-loaded images will be displayed after this 10 seconds.
So i think to specify image sources on the "document.ready" event if the image is cached to display them immediatly.
I found this function : navigator.mozIsLocallyAvailable to check if an image is in the cache. Here is what I've done with jquery :
//specify cached image sources on dom ready
$(document).ready(function() {
var plImages = $(".postLoad");
plImages.each(function() {
var source = $(this).attr("alt")
var disponible = navigator.mozIsLocallyAvailable(source, true);
if (disponible)
$(this).attr("src", source);
});
});
//specify uncached image sources after page loading
$(window).bind('load', function() {
var plImages = $(".postLoad");
plImages.each(function() {
if ($(this).attr("src") == "")
$(this).attr("src", $(this).attr("alt"));
});
});
It works on Mozilla's DOM but it doesn't works on any other one. I tried navigator.isLocallyAvailable : same result.
Is there any alternative?
after some reseach, I found a solution :
The idea is to log the cached images, binding a log function on the images 'load' event.
I first thought to store sources in a cookie, but it's not reliable if the cache is cleared without the cookie. Moreover, it adds one more cookie to HTTP requests...
Then i met the magic : window.localStorage (details)
The localStorage attribute provides
persistent storage areas for domains
Exactly what i wanted :). This attribute is standardized in HTML5, and it's already works on nearly all recent browsers (FF, Opera, Safari, IE8, Chrome).
Here is the code (without handling window.localStorage non-compatible browsers):
var storage = window.localStorage;
if (!storage.cachedElements) {
storage.cachedElements = "";
}
function logCache(source) {
if (storage.cachedElements.indexOf(source, 0) < 0) {
if (storage.cachedElements != "")
storage.cachedElements += ";";
storage.cachedElements += source;
}
}
function cached(source) {
return (storage.cachedElements.indexOf(source, 0) >= 0);
}
var plImages;
//On DOM Ready
$(document).ready(function() {
plImages = $(".postLoad");
//log cached images
plImages.bind('load', function() {
logCache($(this).attr("src"));
});
//display cached images
plImages.each(function() {
var source = $(this).attr("alt")
if (cached(source))
$(this).attr("src", source);
});
});
//After page loading
$(window).bind('load', function() {
//display uncached images
plImages.each(function() {
if ($(this).attr("src") == "")
$(this).attr("src", $(this).attr("alt"));
});
});
The most efficient, simple, and widely supported way to check if an image has already been cached is to do the following...
Create an image object
Set the src property to the desired url
Check the completed attribute immediately to see if the image is already cached
Set the src attribute back to "" (empty string), so that the image is not unnecessarily loaded (unless of coarse you want to load it at this time)
Like so...
function isCached(src) {
const img = new Image();
img.src = src;
const complete = img.complete;
img.src = "";
return complete;
}
In your case, it could be implemented like so...
const lazyImages = document.querySelectorAll(".postLoad");
for (const img of lazyImages) {
if ((!img.src || !isCached(img.src)) && img.getAttribute("alt")) {
img.src = img.getAttribute("alt");
}
}
That being said, I'd advise against using the alt attribute for this purpose, you should use something like data-src instead.
An ajax request for the image would return almost immediately if it is cached. Then use setTimeout to determine if its not ready and cancel the request so you can requeue it for later.
Update:
var lqueue = [];
$(function() {
var t,ac=0;
(t = $("img")).each(
function(i,e)
{
var rq = $.ajax(
{
cache: true,
type: "GET",
async:true,
url:e.alt,
success: function() { var rq3=rq; if (rq3.readyState==4) { e.src=e.alt; } },
error: function() { e.src=e.alt; }
});
setTimeout(function()
{
var k=i,e2=e,r2=rq;
if (r2.readyState != 4)
{
r2.abort();
lqueue.push(e2);
}
if (t.length==(++ac)) loadRequeue();
}, 0);
}
);
});
function loadRequeue()
{
for(var j = 0; j < lqueue.length; j++) lqueue[j].src=lqueue[j].alt;
}
I have a remark about your empty image sources. You wrote:
So i render the page with empty image sources with the source specified in the "alt" attribute. I insert image sources after the "window.onload" event, and it works great.
I've ran into problems with this in the past, because in some browsers empty src attributes cause extra requests. Here's what they do (copied from Yahoo! performance rules, there's also a blog post on that issue with more detail):
Internet Explorer makes a request to the directory in which the page is located.
Safari and Chrome make a request to the actual page itself.
Firefox 3 and earlier versions behave the same as Safari and Chrome, but version 3.5 addressed this issue[bug 444931] and no longer sends a request.
Opera does not do anything when an empty image src is encountered.
We also use a lot of jQuery on our site, and it has not always been possible to avoid empty image tags. I've chosen to use a 1x1 px transparent gif like so: src="t.gif" for images that I only insert after pageload. It is very small and gets cached by the browser. This has worked very well for us.
Cheers, Oliver
Just in case others may come across the same issue. some of the solutions provided here (namely storing the cache info in a local browser data storage) could break for two reasons. Firstly if cache of the image expires and secondly if the cache is cleared by the user. Another approach would be to set the source of image to an placeholder. Then changing the source to the image path/name. This way it becomes the responsibility of the browser to check its own cache. Should work with most browsers regardless of their API.
In 2017, Resource Timing API can help you check this using PerformanceResourceTiming.transferSize property. This property shall return non-zero transfer size when it is downloaded from server (not cached) and returns zero if fetched from a local cache.
Reference : https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/transferSize
For anyone who might be trying to solve this problem with React I used the complete image property to solve it in React this way:
import React, { useState, useEffect, useRef } from 'react'
const Component= () => {
const [isLoadedImage, setLoadedImage] = useState(false)
const imageRef = useRef(null)
useEffect(() => {
const imgEl = imageRef.current
if (imgEl && imgEl.complete && !isLoadedImage) setLoadedImage(true)
})
return (
<img
onLoad={() => (!isLoadedImage ? setLoadedImage(true) : null)}
ref={imageRef}
/>
)
}