How can I catch a 404 error in Javascript? - javascript

I have an HTML audio element and I am dynamically setting the "src" property of the element to an audio file stored on our local area network.
This is how it works:
function setSource(source) {
audio.src = source;
}
var audio = new Audio();
var source = "http://localhost/folder/file.mp3";
setSource(source);
Sometimes, the source audio file that I am pointing to has a broken link and this causes a 404 error to be generated and logged to the browser console.
I want to be able to catch the 404 errors so as to prevent them being logged to the console.
This is how I attempted it:
function setSource(source) {
try {
audio.src = src;
}//end try
catch (e) {
//do nothing
}//end catch
}//end setSource
var audio = new Audio();
var source = "http://localhost/folder/file.mp3";
setSource(source);
Unfortunately, my try/catch statement does absolutely nothing and the error is still logged to the console. Am I doing something wrong?
Due to the nature of my app, there will be lots of 404 errors, which is normal and expected, but it looks really unstable and "ugly" to the users (if they happen to open the console).
FYI: I am using Google Chrome.

In this case, the logging of HTTP errors in the browser console is a feature exclusive to the browser and not of Javascript, or any other website code.
This cannot be prevented.

audio.onload = function() {
console.log('success');
};
audio.onerror = function() {
console.log('fail');
};
audio.src = 'http://localhost/folder/file.mp3';

Yes. With recent updates this is possible. You can enable it here: DevTools->Settings->General->Console->Hide network messages.
How can I catch a 404 error in Javascript?

Related

Playing audio with javascript

I am trying to play a beep sound a minute after user has come on the page of my website. I found the solution here https://stackoverflow.com/a/18628124/912359
Here's my code:
$(document).ready(function(){
setTimeout(function () {
try{
if(!$(".facebook-chat").hasClass("active")){
$(".facebook-chat").addClass("active");
var audio = new Audio("/sound/chat.mp3");
audio.play();
}
}catch(e){
}
}, 60000);
}):
This throws an exception:
Uncaught (in promise) DOMException
Strangely, once I load the sound file separately in my browser and come back to the page, it works perfectly. Any ideas how I can fix it.
[Edit]
The issue is that user has to interact with the browser before the sound can be played. So I put the same code under click event of the body and it works. But the same doesn't work on scroll event either. I guess chrome doesn't consider scroll a user interaction. Can anyone add what other interactions can be used to trigger this?
Also, how is it working if I load the audio file in a separate window and come back to my page.
You can try loading the audio when the document is ready and then play it later only if the resource is loaded (for this check you can register a callback on onloadeddata). Otherwise, if resource is not loaded, you can try loading it again.
$(document).ready(function()
{
let aud = new Audio('https://dl.dropboxusercontent.com/s/1cdwpm3gca9mlo0/kick.mp3');
let canPlay = false;
aud.onloadeddata = () => (console.log("audio loaded"), canPlay = true);
setInterval(function()
{
if (canPlay)
aud.play();
else
aud = new Audio('https://dl.dropboxusercontent.com/s/1cdwpm3gca9mlo0/kick.mp3');
}, 3000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Best solution I could come up with when I tried the same was:
const playPromise = audio.play();
if (playPromise !== null){
playPromise.catch(function() { audio.play(); })
}
But sometimes (One out of ten) the second audio.play() where also uncaught and the audio did not play either. I suggest you made a loop that stops only when the Promise is finally caught.

Detect 404 on video blob:https source

I am using blob:https as source for my video-tags, like this:
function mk_bloburl(source_id, url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob'; //important
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
var source = document.getElementById(source_id);
var video = source;
if (video.tagName=="SOURCE") {
video = source.parentNode;
}
video.oncanplaythrough = function() {
URL.revokeObjectURL(source.src);
};
source.src = URL.createObjectURL(blob);
video.load();
}
};
xhr.send();
}
mk_bloburl('review-video-source', my_video_url );
Having HTML like this:
<video id="review-video" controls="" width="100%">
<source id="review-video-source" />
</video>
Now if I reload the page and start playing, it works. If I play and let it play through and then replay with no wait-time it works.
If I however reload the page and then wait for a while (like 1-2 minutes) and then press play, it fails.
Message I get in the Chrome browser looks like this:
GET blob:https://example.com/debeecfe-49b0-4c98-87d6-8ead325b2d75 404 (Not Found)
So, it's like the blob is auto-removed from the browser memory after a while. I want to catch the event when it is erased or when I get the 404 by starting the playback, so I can refresh the blob.
I have tried:
var source = document.querySelector("#review-video-source");
source.addEventListener("error", function(event) {
console.debug("An error accoured");
});
But this does not seem to catch the error.
What can I do?
Your main problem is caused by the fact you revoked the blobURI in the canplaythrough event.
The canplaythrough event is just a notice sent by the browser to let us know it thinks it will be able to load and play the whole media without interruption ; it doesn't mean that it has loaded everything yet.
In the case of BlobURI, the connection speed is so fast (it comes from memory) that the browser could think it is able to fetch the StarWars saga in 4k in a blink.
So you get this canplaythrough event really early, but the browser didn't actually uncompressed all the data yet. Still, you revoke the BlobURI, and when the browser tries again to fetch data so it can uncompress and read it, there is nothing anymore at the end of the BlobURI's pointer.
So for your problem, you've got two solutions :
In case you need to play the media only once :
call URL.revokeObjectURL(blobURI) in the ended event. This will fire, the first time the currentTime of the video will reach the end.
If you need to play the video multiple times :
revoke the blobURI in the beforeunload event of the page. This way, your BlobURI pointer is always active for as long as the page is alive, but will not block the whole Blob in memory for longer than the page life (which would happen if you don't revoke the BlobURI at all).
And about how to Detect 404 on video blob:https source, I don't really know a good way, except listening for an unexpected jump to the end, but this should not be needed for blobURIs anyway.
One way to get around it is using the fetch API like so :
function mk_bloburl(source_id, url){
fetch(url)//usual get
.then(response=>{
if(response.status == 404)
//Should set here what is an error (ex: x>299)
Promise.reject("Error 404!");
return response.blob();
})//get blob
.then(blobObj=>{//use blob
var blob = blobObj;
var source = focument.getElementById(source_id);
var video = source;
if(video.tagName === "SOURCE")
video = source.parentNode;
video.oncanplaythrough = ()=>{
URL.revokeObjectUrl(source.src);
};
source.src = URL.revokeObjectURL(blob);
video.load();
})
.catch(error=>{
//There has been an error,
//do something about it
//here
});
}

Debugging Web Workers in Safari Web Inspector

Chrome's Dev Tools are great for debugging web workers as I can "browse" into that JavaScript environment and set break points. Even the console works as expected.
On Safari, it is a completely different story. console.log from the web worker doesn't even print in the console. I see the worker script loaded and I put a break point on it, but it doesn't break. I don't even see the scripts that were loaded with importScripts.
How can I use Safari's Web Inspector to troubleshoot problems?
Not that I think it matters, but I'm using Safari 8.
Insert the debugger; code in your source
Usage: Insert it anywhere you want to add a breakpoint and when developer console is open automatically execution will pause at that line
var a = 50;
a = a + 5;
debugger; //--> execution is paused here
a = a - 5;
For more info see the Debugger Documentation on mozilla.org
In lieu of console.log, you can use postMessage. postMessage should allow you to send debug messages to the safari console.
Here is a great example on how to do that, I pasted the main idea below:
//
// In the Main thread
//
var worker = new Worker('/path/of/webworker/code.js')
worker.onmessage = function (e) {
var result = JSON.parse(e.data);
if(result.type == 'debug') {
console.log(result.msg);
} else if(result.type == 'response') {
// ... use result.answer ...
}
}
//
// In the WebWorker
//
function debug(msg) {
postMessage(JSON.stringify({type:'debug',msg:msg}));
}
onmessage = function (e) {
var inputData = e.data;
// work on input data
debug('Working OK');
// work some more
// ...
postMessage(JSON.stringify({type:'response', answer:42}));
};
If you don't want to play around with postMessage though, David Flanagan made a wrapper for it here that should allow you to at least do debugging with console.log

Illegal invocation with start/noteOn using Web Audio API

So basically I've tested this in Chrome and maybe the order of codes is off or whatever, trying to cover some of the functionality of HTML5 audio using "web audio" due to the range requests bug, for the making of games with looping sound effects and music...
I get an "illegal exception" error. Here's the code:
var url='example.mp3';
var a_result=new Object();
a_result.loaded=false;
a_result.evalstring='';
a_result.loop=false;
a_result.play=function(){
var asrc=a_result.source;
asrc.loop=a_result.loop;
//try{
var playfunc=asrc.start||asrc.noteOn;
playfunc(0);
//}catch(e){
/* do nothing */
//}
}
a_result.pause=function(){
var asrc=a_result.source;
try{
var stopfunc=asrc.stop||asrc.noteOff;
stopfunc(0);
}catch(e){
/* do nothing */
}
}
var asrc=actx.createBufferSource();
asrc.connect(actx.destination);
var req=new XMLHttpRequest();
req.open('GET',url,true);
req.responseType='arraybuffer';
req.onload=function(){
if(a_result.loaded==false){
asrc.buffer=actx.createBuffer(req.response,false);
a_result.source=asrc;
a_result.loaded=true;
}
var cont=a_result;
eval(cont.evalstring);
}
req.onerror = function() {
if(a_result.loaded==false){
a_result.loaded=true;
}
}
try{
req.send(null);
}catch(e){
req.onerror();
}
return a_result;
And then later on after the sound has loaded I do something like:
a_result.play();
And instead of playing it gives the error.
Here is a sound test that uses the above code with the fix suggested below, and it works in Chrome, successfully working around the range requests issue on a crappy web server. Here is another that has issues (throwing some kind of "invalid string" error at asrc.buffer=actx.createBuffer(req.response,false); in Iron and silently screwing up in Chrome).
Here is the code edited according to the suggestions:
var url='example.mp3'
var a_result=new Object();
a_result.loaded=false;
a_result.evalstring='';
a_result.loop=false;
a_result.play=function(){
var asrc=a_result.source;
asrc.loop=a_result.loop;
try{
if(asrc.start){
asrc.start(0);
}else{
asrc.noteOn(0);
}
}catch(e){
/* do nothing */
}
}
a_result.pause=function(){
var asrc=a_result.source;
try{
if(asrc.stop){
asrc.stop(0);
}else{
asrc.noteOff(0);
}
}catch(e){
/* do nothing */
}
}
var asrc=actx.createBufferSource();
asrc.connect(actx.destination);
var req=new XMLHttpRequest();
req.open('GET',url,true);
req.responseType='arraybuffer';
req.onload=function(){
actx.decodeAudioData(req.response,function(buffer){
if(buffer){
if(a_result.loaded==false){
asrc.buffer=buffer;
a_result.source=asrc;
a_result.loaded=true;
}
var cont=a_result;
eval(cont.evalstring);
}
});
}
req.onerror = function() {
if(a_result.loaded==false){
a_result.loaded=true;
}
}
try{
req.send(null);
}catch(e){
req.onerror();
}
return a_result;
It no longer appears to have a syntax error, however, it does not seem to solve the playability issues on Chrome (second test case above updated). Specifically, after a sound is stopped it does not want to play again. -- Apparently because it's in the spec. The buffer has to be applied to a new sound source every time you play.
In your new page, you're calling createBuffer(data, false) on the results of an XMLHTTPRequest. You almost certainly want to be calling decodeAudioData() on those results, instead - createBuffer doesn't have a 2-parameter version, and doesn't match the parameters you're passing even if you're trying to push arbitrary data into a buffer. It appears from a browse of your code that you're pulling down MP3 or Ogg files - you need to decode them.
The play method (either start() or noteOn()) needs to be invoked ON the buffersourcenode object, not disassociated from it. You have a few options:
1) I'd strongly recommend just including my audio context monkeypatch library (https://github.com/cwilso/AudioContext-MonkeyPatch/) and using the new (start()) syntax. no muss, no fuss.
2) You can just use an if statement instead of using playfunc to switch:
if (asrc.start)
asrc.start(0);
else
asrc.noteOn(0);
3) You can bind() the play function to the object and keep your code essentially the same:
var playfunc=asrc.start ? asrc.start.bind(asrc) || asrc.noteOn.bind(asrc);
playfunc(0);
4) You can push the playfunc() method onto the object itself (I think this will work):
asrc.playfunc=asrc.start||asrc.noteOn;
asrc.playfunc(0);

Detect failure to load contents of an iframe

I can detect when the content of an iframe has loaded using the load event. Unfortunately, for my purposes, there are two problems with this:
If there is an error loading the page (404/500, etc), the load event is never fired.
If some images or other dependencies failed to load, the load event is fired as usual.
Is there some way I can reliably determine if either of the above errors occurred?
I'm writing a semi-web semi-desktop application based on Mozilla/XULRunner, so solutions that only work in Mozilla are welcome.
If you have control over the iframe page (and the pages are on the same domain name), a strategy could be as follows:
In the parent document, initialize a variable var iFrameLoaded = false;
When the iframe document is loaded, set this variable in the parent to true calling from the iframe document a parent's function (setIFrameLoaded(); for example).
check the iFrameLoaded flag using the timer object (set the timer to your preferred timeout limit) - if the flag is still false you can tell that the iframe was not regularly loaded.
I hope this helps.
This is a very late answer, but I will leave it to someone who needs it.
Task: load iframe cross-origin content, emit onLoaded on success and onError on load error.
This is the most cross browsers origin independent solution I could develop. But first of all I will briefly tell about other approaches I had and why they are bad.
1. iframe That was a little shock for me, that iframe only has onload event and it is called on load and on error, no way to know it is error or not.
2. performance.getEntriesByType('resource'). This method returns loaded resources. Sounds like what we need. But what a shame, firefox always adds Resource in resources array no matter it is loaded or failed. No way to know by Resource instance was it success. As usual. By the way, this method does not work in ios<11.
3. script I tried to load html using <script> tag. Emits onload and onerror correctly, sadly, only in Chrome.
And when I was ready to give up, my elder collegue told me about html4 tag <object>. It is like <iframe> tag except it has fallbacks when content is not loaded. That sounds like what we are need! Sadly it is not as easy as it sounds.
CODE SECTION
var obj = document.createElement('object');
// we need to specify a callback (i will mention why later)
obj.innerHTML = '<div style="height:5px"><div/>'; // fallback
obj.style.display = 'block'; // so height=5px will work
obj.style.visibility = 'hidden'; // to hide before loaded
obj.data = src;
After this we can set some attributes to <object> like we'd wanted to do with iframe. The only difference, we should use <params>, not attributes, but their names and values are identical.
for (var prop in params) {
if (params.hasOwnProperty(prop)) {
var param = document.createElement('param');
param.name = prop;
param.value = params[prop];
obj.appendChild(param);
}
}
Now, the hard part. Like many same-like elements, <object> doesn't have specs for callbacks, so each browser behaves differently.
Chrome. On error and on load emits load event.
Firefox. Emits load and error correctly.
Safari. Emits nothing....
Seems like no different from iframe, getEntriesByType, script....
But, we have native browser fallback! So, because we set fallback (innerHtml) directly, we can tell if <object> is loaded or not
function isReallyLoaded(obj) {
return obj.offsetHeight !== 5; // fallback height
}
/**
* Chrome calls always, Firefox on load
*/
obj.onload = function() {
isReallyLoaded(obj) ? onLoaded() : onError();
};
/**
* Firefox on error
*/
obj.onerror = function() {
onError();
};
But what to do with Safari? Good old setTimeout.
var interval = function() {
if (isLoaded) { // some flag
return;
}
if (hasResult(obj)) {
if (isReallyLoaded(obj)) {
onLoaded();
} else {
onError();
}
}
setTimeout(interval, 100);
};
function hasResult(obj) {
return obj.offsetHeight > 0;
}
Yeah.... not so fast. The thing is, <object> when fails has unmentioned in specs behaviour:
Trying to load (size=0)
Fails (size = any) really
Fallback (size = as in innnerHtml)
So, code needs a little enhancement
var interval = function() {
if (isLoaded) { // some flag
return;
}
if (hasResult(obj)) {
if (isReallyLoaded(obj)) {
interval.count++;
// needs less then 400ms to fallback
interval.count > 4 && onLoadedResult(obj, onLoaded);
} else {
onErrorResult(obj, onError);
}
}
setTimeout(interval, 100);
};
interval.count = 0;
setTimeout(interval, 100);
Well, and to start loading
document.body.appendChild(obj);
That is all. I tried to explain code in every detail, so it may look not so foolish.
P.S. WebDev sucks
I had this problem recently and had to resort to setting up a Javascript Polling action on the Parent Page (that contains the IFRAME tag). This JavaScript function checks the IFRAME's contents for explicit elements that should only exist in a GOOD response. This assumes of course that you don't have to deal with violating the "same origin policy."
Instead of checking for all possible errors which might be generated from the many different network resources.. I simply checked for the one constant positive Element(s) that I know should be in a good response.
After a pre-determined time and/or # of failed attempts to detect the expected Element(s), the JavaScript modifies the IFRAME's SRC attribute (to request from my Servlet) a User Friendly Error Page as opposed to displaying the typical HTTP ERROR message. The JavaScript could also just as easily modify the SRC attribute to make an entirely different request.
function checkForContents(){
var contents=document.getElementById('myiframe').contentWindow.document
if(contents){
alert('found contents of myiframe:' + contents);
if(contents.documentElement){
if(contents.documentElement.innerHTML){
alert("Found contents: " +contents.documentElement.innerHTML);
if(contents.documentElement.innerHTML.indexOf("FIND_ME") > -1){
openMediumWindow("woot.html", "mypopup");
}
}
}
}
}
I think that the pageshow event is fired for error pages. Or if you're doing this from chrome, then your check your progress listener's request to see if it's an HTTP channel in which case you can retrieve the status code.
As for page dependencies, I think you can only do this from chrome by adding a capturing onerror event listener, and even then it will only find errors in elements, not CSS backgrounds or other images.
Doesn't answer your question exactly, but my search for an answer brought me here, so I'm posting just in case anyone else had a similar query to me.
It doesn't quite use a load event, but it can detect whether a website is accessible and callable (if it is, then the iFrame, in theory, should load).
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();
});
Have a id for the top most (body) element in the page that is being loaded in your iframe.
on the Load handler of your iframe, check to see if getElementById() returns a non null value.
If it is, iframe has loaded successfully. else it has failed.
in that case, put frame.src="about:blank". Make sure to remove the loadhandler before doing that.
If the iframe is loaded on the same origin as the parent page, then you can do this:
iframeEl.addEventListener('load', function() {
// NOTE: contentDocument is null if a connection error occurs or if
// X-Frame-Options is not SAMESITE (which could happen with
// 4xx or 5xx error pages if the corresponding error handlers
// do not specify SAMESITE). If error handlers do not specify
// SAMESITE, then networkErrorOccurred will incorrectly be set
// to true.
const networkErrorOccurred = !iframeEl.contentDocument;
const serverErrorOccurred = (
!networkErrorOccurred &&
!iframeEl.contentDocument.querySelector('#well-known-element')
);
if (networkErrorOccurred || serverErrorOccurred) {
let errorMessage;
if (networkErrorOccurred) {
errorMessage = 'Error: Network error';
} else if (serverErrorOccurred) {
errorMessage = 'Error: Server error';
} else {
// Assert that the above code is correct.
throw new Error('networkErrorOccurred and serverErrorOccurred are both false');
}
alert(errorMessage);
}
});

Categories

Resources