From a4091bfe9d1a5e8cf9b24d4768b0f582de52a339 Mon Sep 17 00:00:00 2001 From: Isaiah Odhner Date: Sun, 10 May 2020 17:12:27 -0400 Subject: [PATCH] Use CORS proxy as fallback to load any image URL --- src/functions.js | 47 ++++++++++++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 21 deletions(-) diff --git a/src/functions.js b/src/functions.js index 8ede0b6..75f0af8 100644 --- a/src/functions.js +++ b/src/functions.js @@ -497,23 +497,32 @@ function get_URIs(text) { } function load_image_from_URI(uri, callback){ // @TODO: if URI is not blob: or data:, show dialog with progress bar and this string from mspaint.exe: "Downloading picture" - fetch(uri) - .then(response => response.blob()).then(blob => { - const img = new Image(); - img.crossOrigin = "Anonymous"; - img.onload = ()=> { - if (!img.complete || typeof img.naturalWidth == "undefined" || img.naturalWidth === 0) { - return callback && callback(new Error(`Image failed to load; naturalWidth == ${img.naturalWidth}`)); - } - callback(null, img); - }; - img.onerror = ()=> { + // fetch(uri) + // .then(response => response.blob()).then(blob => { + const img = new Image(); + let trying_cors_proxy = false; + img.crossOrigin = "Anonymous"; + const handle_load_fail = ()=> { + if (trying_cors_proxy) { callback && callback(new Error("Image failed to load")); - }; - img.src = window.URL.createObjectURL(blob); - }).catch((/*error*/) => { - callback && callback(new Error("Image failed to load")); - }); + } else { + trying_cors_proxy = true; + img.src = `https://jspaint-cors-proxy.herokuapp.com/${img.src}`; + } + }; + img.onload = ()=> { + if (!img.complete || typeof img.naturalWidth == "undefined" || img.naturalWidth === 0) { + handle_load_fail(); + return; + } + callback(null, img); + }; + img.onerror = handle_load_fail; + img.src = uri; + //img.src = window.URL.createObjectURL(blob); + // }).catch((/*error*/) => { + // callback && callback(new Error("Image failed to load")); + // }); } function open_from_URI(uri, callback, canceled){ load_image_from_URI(uri, (err, img) => { @@ -722,14 +731,10 @@ function show_error_message(message, error){ // @TODO: close are_you_sure windows and these Error windows when switching sessions // because it can get pretty confusing function show_resource_load_error_message(){ - // NOTE: apparently distinguishing cross-origin errors is disallowed const $w = $FormToolWindow().title("Error").addClass("dialogue-window"); $w.$main.html( "

Failed to load image from URL.

" + - "

Check your browser's devtools for details.

" + - "

Make sure to use an image host that supports " + - "Cross-Origin Resource Sharing" + - ", such as Imgur." + "

Check your browser's devtools for details.

" ); $w.$main.css({maxWidth: "500px"}); $w.$Button("OK", () => {