Display image that returns HTTP 503 in Firefox - html

I have a status badge image that returns the HTTP code 503 when the respective service is offline (but the webserver is still there serving calls). Now opening the image URL directly will display the image properly, regardless of the underlying 503 error code. But using it inside an <img> tag shows the broken image icon. How can I prevent that while still allowing the image itself to return a 503? (External services depend on that)
Here are some screenshots to illustrate what's going on:
The badge on the page:
The status message in the developer console:
The badge itself:
Note: This happens on Firefox. Not Chrome
Edit: Here are a few requested pieces information:
Firefox 78.0.2 (64-Bit)
It's served from the same domain. But the domain is essentially just proxying serveral underlying webservices. And this badge is originating from a different service but all on the same domain.
It's a SVG image if that makes any difference.

Since XMLHttpRequest can retrieve the output of any request, no matter the response code, it is possible to request for the image with XMLHttpRequest, and then convert the blob response type to a base64 format image, which can be loaded in the browser.
The CORS proxy I used in the sample code may not be necessary in the majority of cases, but could be useful in the case where the image you are trying to display has weird response headers that prevent access to the image from another domain.
Here is the sample code. It should work no matter the response code, CORS, etc.
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
// here, reader.result contains the base64-formatted string you can use to set the src attribute with
document.getElementsByTagName('img')[0].src = reader.result; // sets the first <img> tag to display the image, change to the element you want to use
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', "https://cors-anywhere.herokuapp.com/i.stack.imgur.com/8wB1j.png"); // don't include the HTTP/HTTPS protocol in the url
xhr.responseType = 'blob';
xhr.setRequestHeader('X-Requested-With', 'xhr');
xhr.send();
<img src="about:blank">
Everything works, as when you go into Inspect Element, you see that the src attribute of the <img> tag points to a base64 URL that can load in any browser.

You might want to compress or resize your images before uploading it to server , as they might be large enough to keep the server busy and show the error as most of the time, a 503 error occurs because the server is too busy.
More over the image is SVG so it might render dimesions before completing, hence I'd suggest
Try replacing the SVG with PNG or JPG
Also try for site like https://tinypng.com/ to compress the image size
This might work for you

Related

What does "blob" mean in the `href` property in "<link>"? [duplicate]

My page generates a URL like this: "blob:http%3A//localhost%3A8383/568233a1-8b13-48b3-84d5-cca045ae384f" How can I convert it to a normal address?
I'm using it as an <img>'s src attribute.
A URL that was created from a JavaScript Blob can not be converted to a "normal" URL.
A blob: URL does not refer to data the exists on the server, it refers to data that your browser currently has in memory, for the current page. It will not be available on other pages, it will not be available in other browsers, and it will not be available from other computers.
Therefore it does not make sense, in general, to convert a Blob URL to a "normal" URL. If you wanted an ordinary URL, you would have to send the data from the browser to a server and have the server make it available like an ordinary file.
It is possible convert a blob: URL into a data: URL, at least in Chrome. You can use an AJAX request to "fetch" the data from the blob: URL (even though it's really just pulling it out of your browser's memory, not making an HTTP request).
Here's an example:
var blob = new Blob(["Hello, world!"], { type: 'text/plain' });
var blobUrl = URL.createObjectURL(blob);
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function() {
var recoveredBlob = xhr.response;
var reader = new FileReader;
reader.onload = function() {
var blobAsDataUrl = reader.result;
window.location = blobAsDataUrl;
};
reader.readAsDataURL(recoveredBlob);
};
xhr.open('GET', blobUrl);
xhr.send();
data: URLs are probably not what you mean by "normal" and can be problematically large. However they do work like normal URLs in that they can be shared; they're not specific to the current browser or session.
another way to create a data url from blob url may be using canvas.
var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)
as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)
For those who came here looking for a way to download a blob url video / audio, this answer worked for me. In short, you would need to find an *.m3u8 file on the desired web page through Chrome -> Network tab and paste it into a VLC player.
Another guide shows you how to save a stream with the VLC Player.
UPDATE:
An alternative way of downloading the videos from a blob url is by using the mass downloader and joining the files together.
Download Videos Part
Open network tab in chrome dev tools
Reload the webpage
Filter .m3u8 files
Look through all filtered files and find the playlist of the '.ts' files. It should look something like this:
You need to extract those links somehow. Either download and edit the file manually OR use any other method you like. As you can see, those links are very similar, the only thing that differs is the serial number of the video: 's-0-v1-a1.ts', 's-1-v1-a1.ts' etc.
https://some-website.net/del/8cf.m3u8/s-0-v1-a1.ts
https://some-website.net/del/8cf.m3u8/s-1-v1-a1.ts
https://some-website.net/del/8cf.m3u8/s-2-v1-a1.ts
and so on up to the last link in the .m3u8 playlist file. These .ts files are actually your video. You need to download all of them.
For bulk downloading I prefer using the Simple Mass Downloader extension for Chrome (https://chrome.google.com/webstore/detail/simple-mass-downloader/abdkkegmcbiomijcbdaodaflgehfffed)
If you opt in for the Simple Mass Downloader, you need to:
a. Select a Pattern URL
b. Enter your link in the address field with only one modification: that part of the link that is changing for each next video needs to be replaced with the pattern in square brackets [0:400] where 0 is the first file name and 400 is the last one. So your link should look something like this https://some-website.net/del/8cf.m3u8/s-[0:400]-v1-a1.ts.
Afterwards hit the Import button to add these links into the Download List of Mass Downloader.
c. The next action may ask you for the destination folder for EACH video you download. So it is highly recommended to specify the default download folder in Chrome Settings and disable the Select Destination option in Chrome Settings as well. This will save you a lot of time! Additionally you may want you specify the folder where these files will go to:
c1. Click on Select All checkbox to select all files from the Download List.
c2. Click on the Download button in the bottom right corner of the SMD extension window. It will take you to next tab to start downloading
c3. Hit Start selected. This will download all vids automatically into the download folder.
That is it! Simply wait till all files are downloaded and you can watch them via the VLC Player or any other player that supports the .ts format. However, if you want to have one video instead of those you have downloaded, you need to join all these mini-videos together
Joining Videos Part
Since I am working on Mac, I am not aware of how you would do this on Windows. If you are the Windows user and you want to merge the videos, feel free to google for the windows solution. The next steps are applicable for Mac only.
Open Terminal in the folder you want the new video to be saved in
Type: cat and hit space
Open the folder where you downloaded your .ts video. Select all .ts videos that you want to join (use your mouse or cmd+A)
Drag and drop them into the terminal
Hit space
Hit >
Hit Space
Type the name of the new video, e.g. my_new_video.ts. Please note that the format has to be the same as in the original videos, otherwise it will take long time to convert and even may fail!
Hit Enter. Wait for the terminal to finish the joining process and enjoy watching your video!
Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:
function blobToDataURL(blob, callback) {
var fileReader = new FileReader();
fileReader.onload = function(e) {callback(e.target.result);}
fileReader.readAsDataURL(blob);
}
I'm very late to the party.
If you want to download the content you can simply use fetch now
fetch(blobURL)
.then(res => res.blob())
.then(blob => /*do what you want with the blob here*/)
Here the solution:
let blob = new Blob(chunks, { 'type' : 'video/mp4;' });
let videoURL = window.URL.createObjectURL(blob);
const blobF = await fetch(videoURL).then(res => res.blob())
As the previous answer have said, there is no way to decode it back to url, even when you try to see it from the chrome devtools panel, the url may be still encoded as blob.
However, it's possible to get the data, another way to obtain the data is to put it into an anchor and directly download it.
<a href="blob:http://example.com/xxxx-xxxx-xxxx-xxxx" download>download</a>
Insert this to the page containing blob url and click the button, you get the content.
Another way is to intercept the ajax call via a proxy server, then you could view the true image url.

How to use ajax to set the src of an image?

I need to set some headers when getting an image. The img src attribute does not allow this, so I'm using an XHR request to get the image. However, when I set the src attribute on the img tag after that request completes, it looks like the request is triggered again. Is there a way to cache the image and not trigger the second request?
Sample Code:
$(document).ready(function() {
var url = 'https://i.imgur.com/bTaDhpy.jpg'
var file = $.get(url);
file.then(function(data) {
$('#foo').attr('src', url);
});
});
JS Fiddle: https://jsfiddle.net/mehulkar/o4Lcs5Lo/
Note: my question is not about how to set the appropriate headers in the xhr request. My question is how to not trigger another GET from the setting of the src attribute and use the response from the XHR to display the image.
Use the $.ajax for this:
var myImg = $('#foo'),
mySrc = 'https://i.imgur.com/bTaDhpy.jpg';
$.ajax({
url: mySrc,
type: "GET",
headers: {
"X-TOKEN": 'xxxxx'
}
}).done(function() {
myImg.attr('src', mySrc); // set the image source
}).fail(function() {
myImg.hide(); // or something other
});
I cannot comment here due to reputation points, but here is what I've found on this.
I have a local html page that I'm executing via file:///
I can use a $.get to dynamically pull svg files into a variable. The debugger shows this as if it were a standard html node <svg. (I'm using Firefox Developer, but also in Firebug I see the svg file as a node.).
So At this point I have an empty <img that I want to set to my svg file I just don't know how to set the src attribute to the actual document itself. I suppose I could encode to base64.. You might be able to set it using the debugger itself. I couldn't get this to work reliably. Another avenue (for me since I'm using svg) is to clone the object then write it node for node. If you're not using svg perhaps there is some similar hack you could conduct with canvas? Load the image as a sprite then read the colors and set pixels?

detect iframe load error

I am loading a user-selected page into an iframe using the src property. If the load fails, I would like to report the problem in terms that will make sense to the user. iframe does not, in general, support onerror according to http://www.w3schools.com/jsref/dom_obj_frame.asp.
The page may come from the user's domain, not mine, so I cannot view the content of the iframe.
I can set a timeout and cancel it from my onload handler if the load is successful, but it would need to be a long timeout to avoid false error reports, and meanwhile Safari on my iPhone has displayed an alert that may confuse the user. Even this does not work for the Kindle Fire browser - it delivers a load event to my handler regardless of whether the load was successful.
Is there any event I can use to detect failure? Is there any way to suppress the default Safari behavior? Any way I can tell whether the load attempt has failed? (If I could do that, I could use a shorter timeout and poll until the load attempt is resolved).
I can require the use of up to date browsers, but would like a solution that is portable among as many smartphones and tablets as possible.
I have tested the AJAX Get idea, and it unfortunately does not work. A cross-domain AJAX Get to an arbitrary URI results in an exception, regardless of whether the target exists and can be loaded into the iframe or not.
You could set your iframe and/or ajax request to always call a page you control (ie: loader.php), sending loader.php the user's requested page via get. From loader.php, use curl or even just file_get_contents to fetch the external page. If the request fails to come back to loader.php, you can check the error there, and return whatever you want your iframe to display.
While my example references the use of php, curl is supported in a variety of scripting languages. It is likely more complicated than other solutions you might have, but would give you access to the response headers as well for troubleshooting why a page load failed.
As you've hinted, you'll face same-origin-policy type restrictions when you try to query anything inside the iframe if it's on a separate domain.
You could make an AJAX GET request to the iframe's URL before you pass it into the src of the frame. If you don't get an HTTP 200 response back from the AJAX call, then the site won't be able to load inside the frame either.
This will add overhead to the whole process, and is only useful if you're checking whether the iframe's document is a real URL that works. It won't help if you need to know when the iframe document has fully loaded.
If you need to know when the iframe has loaded, and it's on an external domain, then I believe you have no other option but to ask for some code to be added to those external sites to notify the parent page that they've loaded successfully.
Or, if it makes sense to do so, ask the end user to click a link to flag up that the content isn't loading correctly.
Late to the party, but I've managed to crack it:
At first, I thought to do an AJAX call like everyone else, except that it didn't work for me initially, as I had used jQuery. It works perfectly if you do a XMLHttpRequest:
var url = http://url_to_test.com/
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status != 200) {
console.log("iframe failed to load");
}
};
xhttp.open("GET", url, true);
xhttp.send();
Edit:
So this method works ok, except that it has a lot of false negatives (picks up a lot of stuff that would display in an iframe) due to cross-origin malarky. The way that I got around this was to do a CURL/Web request on a server, and then check the response headers for a) if the website exists, and b) if the headers had set x-frame-options.
This isn't a problem if you run your own webserver, as you can make your own api call for it.
My implementation in node.js:
app.get('/iframetest',function(req,res){ //Call using /iframetest?url=url - needs to be stripped of http:// or https://
var url = req.query.url;
var request = require('https').request({host: url}, function(response){ //This does an https request - require('http') if you want to do a http request
var headers = response.headers;
if (typeof headers["x-frame-options"] != 'undefined') {
res.send(false); //Headers don't allow iframe
} else {
res.send(true); //Headers don't disallow iframe
}
});
request.on('error',function(e){
res.send(false); //website unavailable
});
request.end();
});

Chrome extension, replace HTML in response code before browser displays it

i wonder if there is some way to do something like that:
If im on a specific site i want that some of javascript files to be loaded directly from my computer (f.e. file:///c:/test.js), not from the server.
For that i was thinking if there is a possibility to make an extension which could change HTML code in a response which browser gets right before displaying it. So whole process should look like that:
request is made
browser gets response from server
#response is changed# - this is the part when extension comes in
browser parse changed response and display page with that new response.
It doesnt even have to be a Chrome extension anyway. It should just do the job described above. It can block original file and serve another one (DNS/proxy?) or filter whole HTTP traffic in my computer and replace specific code to another one of matched response.
You can use the WebRequest API to achieve that. For example, you can add a onBeforeRequest listener and redirect some requests:
chrome.webRequest.onBeforeRequest.addListener(function(details)
{
var responseData = "<div>Some text</div>"
return {redirectUrl: "data:text/html," + encodeURIComponent(responseData)};
}, {urls: ["https://www.google.com/"]}, ["blocking"]);
This will display a <div> element with the text "some text" instead of the Google homepage. Note that you can only redirect to URLs that the web server itself is allowed to redirect to. This means that redirecting to file:/// URLs is not possible, and you can only redirect to files inside your extension if these are web accessible. data: and http: URLs work fine however.
In Windows you can use the Proxomitron (proxomitron.info) which is a local proxy that can intercept any page or file being loading into your browser and change it using regular expressions (no DOM parsing) however you want, before it is rendered by the browser.

How to set the <img> tag with basic authentication

I would like to display the image from a network camera on my web page, but the image is behind a HTTP basic authentication server.
In Firefox and Chrome I can do this:
<img width="320" height="200" src="http://username:password#server/Path" />
But in Internet Explorer 8, I get an empty image box. If I use JQuery to set the src attribute, IE8 displays a blank src. It looks like IE8 is checking the string and rejecting it.
Is there a way to put the basic authentication credentials in the img tag?
Bottom line: Not all browsers allow this. It may work in some but not others.
But as someone else has said already, it's not very safe -- you're effectively giving the login and password details to anyone who browses the page. Not good.
A better option would be proxy it through the same server that you're providing the html code from, then the href in the <img> tag could just be a local URL, and no-one need know where the image is actually coming from.
You can load your img with AJAX, using XMLHttpRequest. As you might know, XMLHttpRequest has a setRequestHeaders method, so you will be able to manipulate headers for your request, hence, you will be able to do basic HTTP authentication.
Best way is to create a login page, then setup port forwarding on your router to display the camera. Does the camera come with web software?
See http://support.microsoft.com/kb/834489 and http://msdn.microsoft.com/en-us/library/ie/ee330735(v=vs.85).aspx#login_creds_urls
Long story short, usernames/passwords are not formally supported under the HTTP/HTTPS protocol schemes and due to their use in phishing attacks, they were disabled in IE6 on XPSP2. Support can be manually re-enabled by the user using a registry override (FEATURE_HTTP_USERNAME_PASSWORD_DISABLE) but this is not recommended.
Try http proxy.
On server side, enable tinyProxy, create ReversePath to
basic authentication server in configuration like:
AddHeader "Authorization" "Basic dXNlcjpwYXNz"
ReversePath "/foo/" "http://somewhere:3480/foo/"
dXNlcjpwYXNz is base64 encoded string from user:pass
Enable reverse proxy in Apache or NGINX to tinyProxy path http://localhot:8888/foo/
Img Source accessable from local server instead of old way deprecated, without http auth pop-up or CORS error.
http://user:pass#somewhere:3480/foo/DEST.jpg
ajax add http header works!
pictureUrl = "https://somewhere/file.jpg";
var oReq = new XMLHttpRequest();
oReq.open("GET", pictureUrl, true);
oReq.setRequestHeader("Authorization", "Basic " + btoa("UserName"+":"+"Password"));
// use multiple setRequestHeader calls to set multiple values
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response; // Note: not oReq.responseText
if (arrayBuffer) {
var u8 = new Uint8Array(arrayBuffer);
var b64encoded = btoa(String.fromCharCode.apply(null, u8));
var mimetype="image/jpeg"; // or whatever your image mime type is
document.getElementById("iOdata").src="data:"+mimetype+";base64,"+b64encoded;
}
};
oReq.send(null);