Catch window.open() error - javascript

I open a file download from a remote API on my webpage via window.open(). The API (a Flask server) has error handling and returns the error message if there's an internal server error, like this:
#app.errorhandler(502) //all other errors are handled the same way, including 500, etc.
#crossdomain(origin='*')
def bad_gateway_error(error):
return "Bad Gateway Error - Please make sure you're using a properly formatted file! Details: " + str(error), 200
I want to display this error on my site instead of redirecting to the error page. I'm trying to catch it via:
try {
window.open("https://API/receivedoc?timestamp="+timestamp,"_self")
} catch(e) {
filerootdiv.querySelector('.output').innerHTML = String(e);
}
This however does nothing (tested in Chrome). How could I catch the error when I'm using window.open? I guess it might be because in the error handling I return a 200 message so that the string I return actually gets returned instead of just crashing the server (this needs to stay this way as it's working just fine with all the other errors when I'm not trying to return a file). The issue is that I can't tell if the API request would return a file or a string before doing a window.open().
UPDATE
I've tried implementing:
let new_window = window.open("https://flaskmin.run.aws-usw02-pr.ice.predix.io/receivedoc?timestamp="+timestamp,"_self")
newWindow.onerror = function() {
filerootdiv.querySelector('.output').innerHTML = "Error!";
However this still only opens a new window with the error. I guess it's because of the error handling on the server side (I cannot change this). Can I somehow probe the content of new_window before redirecting to it, and just not open it if it's just a string containing the word 'error'?

Related

Is there a way to detect if the browser has a mailto protocol handler set?

I have a site that dynamically builds a mailto url which it then opens in a new tab/window, using window.open().
window.open("mailto:" + encodeURIComponent(r["to"]));
I'm testing in Chrome at this stage, so other browsers may act differently.
If Chrome has a mailto protocol handler set up (e.g. GMail), then it works as expected.
If Chrome does not have a mailto protocol handler set up, it just opens a tab with the mailto url and nothing else.
That's not the worst result, but it would be nice if there was a way of knowing in advance, so that the user could be in some way guided to setting up their browser so that the mailto url worked nicely.
Previously, I was just opening in the same page by setting window.location.href to the url:
windows.location.href = "mailto:" + encodeURIComponent(r["to"]);
This wasn't great because if there was no protocol handler set, nothing happened. I also would consider this as an option, IF I can at least detect the situation, but wasn't able to find any indication of that either. I guess one option would be to set a timer which if it reached execution could alert the user?
Anyone else already solved this? Seems like a pretty common requirement.
Thanks
Here's what I ended up working with. It doesn't work in all cases, but provides at least some help in recognising unhandled protocols.
It attempts to open the URL in a new window and then after 2s it takes a look to see if it can read the location. If it has opened a third party site (e.g. GMail) this will raise and exception - so we treat this as success.
If no exception occurs, this returns "about:blank" which means we (probably) failed.
function openWin(url) {
return new Promise((resolve, reject) => {
const w = window.open(url);
if (!w) {
reject();
}
setTimeout(function() {
try {
const working = w.document.location.href;
} catch (e) {
resolve();
return;
}
w.close();
reject();
}, 2000);
});
}
Called with something like this:
openWin('mailto:' + encodeURIComponent(to)).then(() => {
// handle success
}).catch(() => {
// handle failure
});
Caveat: This only works for web-based protocol handlers. If for example your mailto is handled by an email app, then this will fail.
In my case, most people would be using web-based email, so it works for most cases. On failure I show a message to the affect of "If your email didn't open, copy the email address here..."

How to postMessage from Firefox frame-script to a web page?

i'm adjusting my extension to Firefox multiprocess (e10s).
I want to send the webpage some data using a postMessage from the frame-script.
The Firefox documnatation says i should try to use 'content' object instead of the 'window' object. When trying to access the content page i get an error: .
// frame-script.js
addMessageListener("message_from_ext", function(message){
try{
var _message = {
from: "content",
to: "web",
data: message
};
content.postMessage(_message, "*"); //getting <unavailable> on the content object
}catch(e){
console.log(e);
}
});
how should i access the content object? should i load anything to my frame-script.js?
(I already succeeded in getting data from the webpage, and sending it to the extension and getting back other data from the extension)
<unavailable> is not an error, it just means the console you have open cannot display the object properly because it lives in another process.
Open the browser content toolbox and use its console instead to view messages in the content process.

How to catch HTTPS errors in $('<img/>').onLoad()

I try to maintain a strict "clean error log" policy in my web pages, for my own sanity as well as for end-users' confidence in the page.
Is there a way to trap HTTP errors when loading remote content into a page element?
My code looks like this :
/* Vew validation rule added to jQuery Validation */
$.validator.addMethod(
"remoteImage" // This is the name of the new rule, applied to 'val_ImageURL' below.
, function (url, element) {
$('#divImageURLresult').removeClass("invalid").removeClass("validated"); // Clear previous simulated validation results
$('<img/>').attr('src', url).on("load", function() {
$('#editImageHeight').val(this.height);
$('#editImageWidth').val(this.width);
$('#divImageURLresult').html("Height : " + this.height + ". Width : " + this.width);
$('#divImageURLresult').addClass("validated"); // Simulated validation result
}).error(function() {
$('#editImageHeight').val("Unknown"); // Force validation to fail. Height can only be a number.
$('#divImageURLresult').html("Not an image.");
$('#divImageURLresult').addClass("invalid"); // Simulated validation result
});
return true; // Always return true since we get here before the image load callback returns.
}
, "");
Example bad value log :
The page at
'https://docs.google.com/spreadsheets/d/1RI5j_aIBipv3En8s/edit#gid=7042'
was loaded over HTTPS, but displayed insecure content from
'http://i.imgur.com/Xgng8S9.pig': this content should also be loaded
over HTTPS.
GET http://imgur.com/Xgng8S9.pig 404 (Not Found)
There is no way to NOT use HTTPS for Google HTMLService pages. but there is also no way to ensure users will only load HTTPS pages.
I should handle those types of error internally, it seems to me. How do I do it?
Also, is the "... but displayed insecure content ..." message enforced to be available to the end-user?

Jsdom throws an error on a external resource script (script on the page) after returning the result

I am getting an error which seems to be originating from one of the page scripts.
file://cdn.widgets.webengage.com/js/widget/webengage-min-v-3.0.js:1
return c.apply(undefined,a)}catch(d){webengage.eLog(d);if(!b){throw d}}}else{t
^
TypeError: Cannot call method 'call' of undefined
at new exports.NOT_IMPLEMENTED (/usr/local/lib/node_modules/jsdom/lib/jsdom/browser/utils.js:9:13)
at Object.webengage.eLog (file://cdn.widgets.webengage.com/js/widget/webengage-min-v-3.0.js:1:366)
at t.extend.u (file://cdn.widgets.webengage.com/js/widget/webengage-min-v-3.0.js:1:19160)
at Object.t.extend.error (file://cdn.widgets.webengage.com/js/widget/webengage-min-v-3.0.js:1:19299)
at file://cdn.widgets.webengage.com/js/widget/webengage-min-v-3.0.js:1:66518
at Object.webengage.withELog (file://cdn.widgets.webengage.com/js/widget/webengage-min-v-3.0.js:1:640)
at Timer.<anonymous> (file://cdn.widgets.webengage.com/js/widget/webengage-min-v-3.0.js:1:937)
at Timer.exports.setInterval.timer.ontimeout (timers.js:234:14)
I am getting this error from the following code:
try {
var document = jsdom.jsdom(str, null, {});
} catch(e) {
console.log("Got ERROR...");
console.log(e);
}
console.log("Page Document Loaded.");
var window = document.parentWindow;
//console.log(window.document.innerHTML);
console.log(window.innerWidth);
console.log(typeof window.document.getElementsByClassName);
here str is the html that i got earlier. I am able to see printed results, the html the innerWidth and the typeof getElementsByClassName i.e.. function. But after around 20 seconds i am getting the above error and my application crashes, without printing Got ERROR... from above.
The first question that i have is why is my application still running after printing the last thing. Is this a normal behavior for jsdom that it keeps on running like how in a browser a script keeps on running until window.close() is given.
The actual problem is, how can i resolve this. I want to trigger few events in this window object and interact with it but it keeps on crashing.
The url for the script is a little confusing:
file://cdn.widgets.webengage.com/js/widget/webengage-min-v-3.0.js:1
this is because the page is fetching this script resource in an ajax call with the url:
//cdn.widgets.webengage.com/js/widget/webengage-min-v-3.0.js:1
although jsdom is able to get the resource, i checked that this script has that line where it is showing the error.

Eliminate 404 url error in console?

I try to eleminate an 404 error occuring because the source (src) is missing..
var $chart = $("<img />")
.addClass("trend-pic")
.error(function(){
console.log("error loading..")
});
try{
$chart.attr("src", jobs[counter].url + "test/trend")
}catch(err){
$chart.attr("src", "");
}
if tried many stuff to catch the error i.e. putting an .error(function(){}) at the end.
use the $chart.load() - method to check if the images gets loaded?
Non of those helped?
GET {myURLString} 404 (Not Found)
Browser: Safari
You can't really delete those 404 errors from the console.
The best you can do is make some ajax calls and see the return code, but then you'll be limited to request only to your own domain.
EDIT--
Oh, and yes, those errors will keep showing in the "Requests" tab! They just won't appear in the "Console" tab (in Chrome).
I think there is no way to eliminate the error from your console, except using the right url.
In your code with the try {} catch() the error is thrown and $chart.attr will be called again with an empty string.
What you can do is add a check like this before you set the .attr()
if (jobs[counter].url !== void 0 &&
jobs[counter].url.length !== 0) {
$chart.attr("src", jobs[counter].url + "test/trend")
}
so you can remove the try{} catch()
Hope it helps.
Just the answer is No.Because this is the only way Server send "there is a Error".
Refer this one.
Prevent 404 Error in console
404 is not an error. It is the way server says it does not have the source referred by the client.

Categories