Image Replacement (JS/JQuery) working in IE but not FF - javascript

I have tried multiple solutions for replacing broken images (both JS & jQuery) and all work perfectly with IE but not in FF, is there a reason for this?
Are images handled differently in FF that may cause this?
JQuery Example:
$("img").error(function(){
$(this).unbind("error").attr("src", "nopic.jpg");
});
Javascript Example: (triggered by onError event in img tag)
function noimage(img){
img.onerror="";
img.src="nopic.jpg";
return true; }
Both of these examples work perfectly in IE but not at all in FF. What gives?
Thanks in advance!

You're testing locally, aren't you, by pointing at a file URL?
Try testing on an actual server, even if it's just local. I believe that Firefox relies on the HTTP status code returned from the image GET to trigger an error; if you're loading from a file://... URL there's no server involved, so you don't get the error.
From the jQuery API docs for error():
This event may not be correctly fired when the page is served locally. Since error relies on normal HTTP status codes, it will generally not be triggered if the URL uses the file: protocol.
EDIT: As we've discussed in the comments, this appears to be because for some reason your intranet server is not responding to a missing resource with a 404 (or any other error, by the sounds of things.)
Because Firefox doesn't receive an error, it doesn't trigger the error handler, which seems like sane behaviour.
I think your problem just became "my server doesn't return 404 errors for missing content", but you might need to experiment a bit more to gather evidence before asking that one (and possibly ask it on Serverfault rather than on SO...)

You have to bind the error handler first, before setting the src of an image. So setting the src in HTML and then bind it via JavaScript is not working.
You can prove this for yourself: http://jsfiddle.net/4Wcnj/2/.
HTML:
<img width=500 id=img height=500 src="missing1">
JavaScript:
// At this point, missing1 is having an error, but no handler set so far
$("#img").error(function() {
alert("Missing: " + $(this).attr("src"));
});
// The bind handler has been set, now if you set the src wrongly, you
// get the alert
$("img").attr("src", "missing2");

Related

How can I cancel consecutive requests to my server? [duplicate]

What would cause a page to be canceled? I have a screenshot of the Chrome Developer Tools.
This happens often but not every time. It seems like once some other resources are cached, a page refresh will load the LeftPane.aspx. And what's really odd is this only happens in Google Chrome, not Internet Explorer 8. Any ideas why Chrome would cancel a request?
We fought a similar problem where Chrome was canceling requests to load things within frames or iframes, but only intermittently and it seemed dependent on the computer and/or the speed of the internet connection.
This information is a few months out of date, but I built Chromium from scratch, dug through the source to find all the places where requests could get cancelled, and slapped breakpoints on all of them to debug. From memory, the only places where Chrome will cancel a request:
The DOM element that caused the request to be made got deleted (i.e. an IMG is being loaded, but before the load happened, you deleted the IMG node)
You did something that made loading the data unnecessary. (i.e. you started loading a iframe, then changed the src or overwrite the contents)
There are lots of requests going to the same server, and a network problem on earlier requests showed that subsequent requests weren't going to work (DNS lookup error, earlier (same) request resulted e.g. HTTP 400 error code, etc)
In our case we finally traced it down to one frame trying to append HTML to another frame, that sometimes happened before the destination frame even loaded. Once you touch the contents of an iframe, it can no longer load the resource into it (how would it know where to put it?) so it cancels the request.
status=canceled may happen also on ajax requests on JavaScript events:
<script>
$("#call_ajax").on("click", function(event){
$.ajax({
...
});
});
</script>
<button id="call_ajax">call</button>
The event successfully sends the request, but is is canceled then (but processed by the server). The reason is, the elements submit forms on click events, no matter if you make any ajax requests on the same click event.
To prevent request from being cancelled, JavaScript event.preventDefault(); have to be called:
<script>
$("#call_ajax").on("click", function(event){
event.preventDefault();
$.ajax({
...
});
});
</script>
NB: Make sure you don't have any wrapping form elements.
I had a similar issue where my button with onclick={} was wrapped in a form element. When clicking the button the form is also submitted, and that messed it all up...
Another thing to look out for could be the AdBlock extension, or extensions in general.
But "a lot" of people have AdBlock....
To rule out extension(s) open a new tab in incognito making sure that "allow in incognito is off" for the extention(s) you want to test.
In my case, I found that it is jquery global timeout settings, a jquery plugin setup global timeout to 500ms, so that when the request exceed 500ms, chrome will cancel the request.
You might want to check the "X-Frame-Options" header tag. If its set to SAMEORIGIN or DENY then the iFrame insertion will be canceled by Chrome (and other browsers) per the spec.
Also, note that some browsers support the ALLOW-FROM setting but Chrome does not.
To resolve this, you will need to remove the "X-Frame-Options" header tag. This could leave you open to clickjacking attacks so you will need to decide what the risks are and how to mitigate them.
Here's what happened to me: the server was returning a malformed "Location" header for a 302 redirect.
Chrome failed to tell me this, of course. I opened the page in firefox, and immediately discovered the problem.
Nice to have multiple tools :)
Another place we've encountered the (canceled) status is in a particular TLS certificate misconfiguration. If a site such as https://www.example.com is misconfigured such that the certificate does not include the www. but is valid for https://example.com, chrome will cancel this request and automatically redirect to the latter site. This is not the case for Firefox.
Currently valid example: https://www.pthree.org/
A cancelled request happened to me when redirecting between secure and non-secure pages on separate domains within an iframe. The redirected request showed in dev tools as a "cancelled" request.
I have a page with an iframe containing a form hosted by my payment gateway. When the form in the iframe was submitted, the payment gateway would redirect back to a URL on my server. The redirect recently stopped working and ended up as a "cancelled" request instead.
It seems that Chrome (I was using Windows 7 Chrome 30.0.1599.101) no longer allowed a redirect within the iframe to go to a non-secure page on a separate domain. To fix it, I just made sure any redirected requests in the iframe were always sent to secure URLs.
When I created a simpler test page with only an iframe, there was a warning in the console (which I had previous missed or maybe didn't show up):
[Blocked] The page at https://mydomain.com/Payment/EnterDetails ran insecure content from http://mydomain.com/Payment/Success
The redirect turned into a cancelled request in Chrome on PC, Mac and Android. I don't know if it is specific to my website setup (SagePay Low Profile) or if something has changed in Chrome.
Chrome Version 33.0.1750.154 m consistently cancels image loads if I am using the Mobile Emulation pointed at my localhost; specifically with User Agent spoofing on (vs. just Screen settings).
When I turn User Agent spoofing off; image requests aren't canceled, I see the images.
I still don't understand why; in the former case, where the request is cancelled the Request Headers (CAUTION: Provisional headers are shown) have only
Accept
Cache-Control
Pragma
Referer
User-Agent
In the latter case, all of those plus others like:
Cookie
Connection
Host
Accept-Encoding
Accept-Language
Shrug
I got this error in Chrome when I redirected via JavaScript:
<script>
window.location.href = "devhost:88/somepage";
</script>
As you see I forgot the 'http://'. After I added it, it worked.
Here is another case of request being canceled by chrome, which I just encountered, which is not covered by any of answers up there.
In a nutshell
Self-signed certificate not being trusted on my android phone.
Details
We are in development/debug phase. The url is pointing to a self-signed host. The code is like:
location.href = 'https://some.host.com/some/path'
Chrome just canceled the request silently, leaving no clue for newbie to web development like myself to fix the issue. Once I downloaded and installed the certificate using the android phone the issue is gone.
If you use axios it can help you
// change timeout delay:
instance.defaults.timeout = 2500;
https://github.com/axios/axios#config-order-of-precedence
For my case, I had an anchor with click event like
<a href="" onclick="somemethod($index, hour, $event)">
Inside click event I had some network call, Chrome cancelling the request. The anchor has href with "" means, it reloads the page and the same time it has click event with network call that gets cancelled. Whenever i replace the href with void like
<a href="javascript:void(0)" onclick="somemethod($index, hour, $event)">
The problem went away!
If you make use of some Observable-based HTTP requests like those built-in in Angular (2+), then the HTTP request can be canceled when observable gets canceled (common thing when you're using RxJS 6 switchMap operator to combine the streams). In most cases it's enough to use mergeMap operator instead, if you want the request to complete.
I had faced the same issue, somewhere deep in our code we had this pseudocode:
create an iframe
onload of iframe submit a form
After 2 seconds, remove the iframe
thus, when the server takes more than 2 seconds to respond the iframe to which the server was writing the response to, was removed, but the response was still to be written , but there was no iframe to write , thus chrome cancelled the request, thus to avoid this I made sure that the iframe is removed only after the response is over, or you can change the target to "_blank".
Thus one of the reason is:
when the resource(iframe in my case) that you are writing something in, is removed or deleted before you stop writing to it, the request will be cancelled
I have embedded all types of font as well as woff, woff2, ttf when I embed a web font in style sheet. Recently I noticed that Chrome cancels request to ttf and woff when woff2 is present. I use Chrome version 66.0.3359.181 right now but I am not sure when Chrome started canceling of extra font types.
We had this problem having tag <button> in the form, that was supposed to send ajax request from js. But this request was canceled, due to browser, that sends form automatically on any click on button inside the form.
So if you realy want to use button instead of regular div or span on the page, and you want to send form throw js - you should setup a listener with preventDefault function.
e.g.
$('button').on('click', function(e){
e.preventDefault();
//do ajax
$.ajax({
...
});
})
I had the exact same thing with two CSS files that were stored in another folder outside my main css folder. I'm using Expression Engine and found that the issue was in the rules in my htaccess file. I just added the folder to one of my conditions and it fixed it. Here's an example:
RewriteCond %{REQUEST_URI} !(images|css|js|new_folder|favicon.ico)
So it might be worth you checking your htaccess file for any potential conflicts
happened to me the same when calling a. js file with $. ajax, and make an ajax request, what I did was call normally.
In my case the code to show e-mail client window caused Chrome to stop loading images:
document.location.href = mailToLink;
moving it to $(window).load(function () {...}) instead of $(function () {...}) helped.
In can this helps anybody I came across the cancelled status when I left out the return false; in the form submit. This caused the ajax send to be immediately followed by the submit action, which overwrote the current page. The code is shown below, with the important return false at the end.
$('form').submit(function() {
$.validator.unobtrusive.parse($('form'));
var data = $('form').serialize();
data.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
if ($('form').valid()) {
$.ajax({
url: this.action,
type: 'POST',
data: data,
success: submitSuccess,
fail: submitFailed
});
}
return false; //needed to stop default form submit action
});
Hope that helps someone.
For anyone coming from LoopbackJS and attempting to use the custom stream method like provided in their chart example. I was getting this error using a PersistedModel, switching to a basic Model fixed my issue of the eventsource status cancelling out.
Again, this is specifically for the loopback api. And since this is a top answer and top on google i figured i'de throw this in the mix of answers.
For me 'canceled' status was because the file did not exist. Strange why chrome does not show 404.
It was as simple as an incorrect path for me. I would suggest the first step in debugging would be to see if you can load the file independently of ajax etc.
The requests might have been blocked by a tracking protection plugin.
It happened to me when loading 300 images as background images. I'm guessing once first one timed out, it cancelled all the rest, or reached max concurrent request. need to implement a 5-at-a-time
One the reasons could be that the XMLHttpRequest.abort() was called somewhere in the code, in this case, the request will have the cancelled status in the Chrome Developer tools Network tab.
In my case, it started coming after chrome 76 update.
Due to some issue in my JS code, window.location was getting updated multiple times which resulted in canceling previous request.
Although the issue was present from before, chrome started cancelling request after update to version 76.
I had the same issue when updating a record. Inside the save() i was prepping the rawdata taken from the form to match the database format (doing a lot of mapping of enums values, etc), and this intermittently cancels the put request. i resolved it by taking out the data prepping from the save() and creating a dedicated dataPrep() method out of it. I turned this dataPrep into async and await all the memory intensive data conversion. I then return the prepped data to the save() method that i could use in the http put client. I made sure i await on dataPrep() before calling the put method:
await dataToUpdate = await dataPrep();
http.put(apiUrl, dataToUpdate);
This solved the intermittent cancelling of request.

How to fake a HTML5 video element to error to test error handling

I'm currently developing an HTML5 video player and hooked up the error event listener, however so far there has been no errors.
Is there a way to fake/simulate an error, to test that it's working correctly?
Perhaps a method I can call to force it to error?
There are no method to simulate errors from within the browser. You'll have to setup the environment itself to simulate errors (both for error as well as the abort event):
Create two faulty files: one which has container error (truncate the file size) and one with encoding error (hex edit the file and override some of the data)
Additionally use an URL to a non-existing file
Setup a server script which can terminate the serving of the file or take the test-site down
Setup a script that can disable the net interface
Then run specific tests for each scenario to see how your code behaves.
A custom event can be dispatched but the problem is that it won't prevent the browser from loading the file which means you still can get a load event etc. which would be conflicting.
You can generate an abort event by changing the video source while the video is playing - which is possibly (if you allow swapping sources for the same media element) something you would need to handle as it's not technically an error in that case.
I'm not aware of any built-in method to simulate an error. I suppose you could create an error event and dispatch it to one of your <source> elements.
function simulateError() {
// I'm not sure if it would be better to use ErrorEvent()
// Using Chrome devtools, this gives an error event that appears
// almost identical to having a source that gets a 404
var event = new Event('error', {
'view': window,
'cancelable': true
});
var src = document.getElementById('sourceElement');
src .dispatchEvent(event);
}
Another way would be to follow #andlrc's advice: give it a broken video or cut the internet. I get an error when the source is invalid, so you could try that too.

Replacing entire page via AJAX causes Permission Denied error in IE only

I have an AJAX post that retrieves data from the server and either replaces part of the page or in some cases the full page. This is controlled by a javascript fullRefresh parameter. The problem is the refresh code works find in Firefox but causes a Permission Denied error in the bowels of JQuery after it runs in IE although it would appear to actually replace the page contents successfully.
IE version 11.0.9600.16659
JQuery version 1.8.2
Error message
Unhandled exception at line 2843, column 3 in http://localhost:62761/Scripts/jquery-1.8.2.js
0x800a0046 - JavaScript runtime error: Permission denied
My code is
function RefreshScreenContent(formActionUrl, formHTML, fullRefresh) {
fullRefresh = (typeof fullRefresh === "undefined") ? false : fullRefresh;
if (fullRefresh) {
document.write(formHTML);
document.close();
}
else {
$("#content-parent").html(formHTML);
}
}
The partial refreshes work fine but the full refreshes are the problem. I have tried hardcoding the document.write call to write a well formed simple html page rather than formHTML in case that was somehow the problem but even a simple single word page causes the error.
The actual error occurs a some point later with a callback inside JQuery.
The AJAX post to the server is in the same application i.e. is not a cross domain request. I have seen posts online talking aboue cross domain stuff that is not applicable here.
Can anyone tell me why this is happening and how to stop it? Is there an alternative IE way of replacing the page contents?
Your code is fine (at least at first glance). My guess is that you make the call in such a way, that it is interpreted as cross-domain.
I would suggest checking:
http vs https (most common)
the destination port
the root url
maybe the "destination" page makes some requests of its own, check to be on same domain
The reason why IE may be the only one with the problem is that it has higher security demanding by default that other browsers (check advanced security settings - can't remember where they are put in menu) so it interprets requests in a more "paranoid" manor.
I repeat, what I said is just a guess, based on cases I've been put into.
In the end I used the approach here to replace the body tag in the pgae with the one in the markup the AJAX receives back https://stackoverflow.com/a/7839921/463967
I would have preferred to replace all content not just the body but I can always adapt later to include the header etc as body is enough for my uses right now. This works in IE and Firefox.

JSONP and DOCTYPE Errors

I'm running into a weird problem.
I'm communicating with my server using AJAX. (I'm running my web application on localhost).
Server is located on, say, http://www.example.com
To bypass the Same Origin Policy, I'm using JSONP. I dynamically create a <script> tag and load the data from my server.
So far so good.
Then I decided to upload my web application to this subdomain: http://m.example.com
That's when I run into crazy errors. Sometimes the page loads, sometimes it doesn't. When it doesn't load, Firebug throws a DOCTYPE error.
I did some research and came across this stackoverflow post: firebug returns syntax error in doctype?
Quoting an answer in this link:
This usually happens because you are loading an HTML document as a script. This is often caused by <script src=""></script> (i.e. a relative URI pointing at the current, HTML, document)) or one of the scripts pointing to a 404 error.
Pretty helpful stuff. Based on all that, I've concluded from all the above that whenever my server responds slowly, the <script> tag's src attribute is null. Since that throws a 404 error, I get a DOCTYPE error in Firebug. Whenever my server responds quickly, there are no issues and everything works fine.
How do I solve this problem? I could put a manual timeout or something, but that wouldn't exactly be foolproof and an elegant solution.
Any help guys?
EDIT:
Here's some code:
This function is used to create the script tag dynamically:
function appendScriptToHead() {
var element = document.createElement("script");
element.src = 'http://www.example.com/?data&callback=callfunction';
document.getElementsByTagName("head")[0].appendChild(element)
}
This callback function is called when the above url containing JSONP data is loaded:
function callfunction(response) {
alert(response);
}
I think there's a bit of misunderstanding here. Your script element will always have its src property set, but its contents depends on your server's response. I doubt it'll be error 404 (as it refers to the element not found, which is hardly repetitive), but it can be of 500 flavors.
I suggest debugging your queries just as they are (i.e., opening http://www.example.com/?data&callback=%callfunction% with your browser or some scripted HTTP UserAgent, if you feel industrious), to see what might be wrong with the logic which selects the script to be loaded.

What might cause an XMLHttpRequest to never change state in Firefox?

I'm working on some old AJAX code, written in the dark dark days before jQuery. Strangely, it has been working fine for years, until today when it suddenly stopped firing its callback. Here's the basic code:
var xml = new XMLHttpRequest(); // only needs to support Firefox
xml.open("GET", myRequestURL, true);
xml.onreadystatechange = function() { alert ('test'); };
xml.send(null);
Checking the Firebug console, the request is being sent with no worries, and it is receiving the correct XML from the request URL, but the onreadystatechange function is not working at all. There's no javascript errors or anything else strange happening in the system.
I wish I could just rewrite everything using jQuery, but I don't have the time right now. What could possibly be causing this problem??
A further update - I've been able to test my code in a different browser (FFx 3.0) and it was working there, so it must be a problem with my browser. I'm running Firefox 3.5b4 on Vista, and I've tried it now with all my addons disabled with no luck. It's still really bugging me because I was working on this site yesterday (with the same browser setup) and there were no problems at all...
Actually I just took a look back in my Addons window and saw that Firebug was still enabled. If I disable Firebug, it works perfectly. If I enable it, it's broken. Firebug version 1.40.a31
is the url malformed?
have you tried putting the whole thing in a try-catch and alerting the errors (if any)
is it failing on an authorization check?
does the url in question require http-auth? (though there should be state changes in this case, I'll admit)
edit:
I have a really funny thought here. Are you using firefox 3.5 beta4? I develop a firefox extension for a browser-based game and recently discovered some odd behvaviour. With my extension or firebug observing the ajax requests made from the page, the script ccreating them would never get calledback. The request would be correctly observed and processed by both firebug and my extension (I could observe what was sent and received)... but the page itself would never hear from the request again -- like it had disappeared into a black hole.
Try turning off firebug (or at least turn off listening to 'Net' for that domain) and test it again
Known Firefox bug affecting Firebug; see http://code.google.com/p/fbug/issues/detail?id=1569&q=xhr&colspec=ID%20Type%20Status%20Owner%20Test%20Summary for details :-)
It seems unlikely that onreadystatechange would stop working. Is it possible that the 'alert' function has somehow been disabled or overridden? Can you replace the alert with some code to make a visible change in the page, and check its functionality that way? (I know, its a stretch, but it just seems so strange that onreadystatechange wouldn't work!)

Categories

Resources