2018-05-18 03:25:45 +00:00
|
|
|
/* globals jQuery */
|
|
|
|
const $ = jQuery;
|
2018-05-16 00:53:27 +00:00
|
|
|
$('a').click(function () {
|
2018-05-18 03:25:45 +00:00
|
|
|
const {href} = this;
|
|
|
|
const target = window.parent;
|
|
|
|
const post = (message) => {
|
|
|
|
// Todo: Make origin customizable as set by opening window
|
|
|
|
// Todo: If dropping IE9, avoid stringifying
|
|
|
|
target.postMessage(JSON.stringify({
|
|
|
|
namespace: 'imagelib',
|
|
|
|
...message
|
|
|
|
}), '*');
|
|
|
|
};
|
2018-05-18 04:54:31 +00:00
|
|
|
// Convert Non-SVG images to data URL first
|
|
|
|
// (this could also have been done server-side by the library)
|
2018-05-18 03:25:45 +00:00
|
|
|
// Send metadata (also indicates file is about to be sent)
|
|
|
|
post({
|
|
|
|
name: $(this).text(),
|
|
|
|
id: href
|
|
|
|
});
|
2018-09-25 06:21:40 +00:00
|
|
|
if (!href.includes('.svg')) {
|
2018-05-18 03:25:45 +00:00
|
|
|
const img = new Image();
|
2018-05-18 04:54:31 +00:00
|
|
|
img.onload = function () {
|
2018-05-18 03:25:45 +00:00
|
|
|
const canvas = document.createElement('canvas');
|
2018-05-18 04:54:31 +00:00
|
|
|
canvas.width = this.width;
|
|
|
|
canvas.height = this.height;
|
|
|
|
// load the raster image into the canvas
|
|
|
|
canvas.getContext('2d').drawImage(this, 0, 0);
|
|
|
|
// retrieve the data: URL
|
2018-05-18 03:25:45 +00:00
|
|
|
let data;
|
2018-05-18 04:54:31 +00:00
|
|
|
try {
|
2018-05-18 03:25:45 +00:00
|
|
|
data = canvas.toDataURL();
|
2018-05-18 04:54:31 +00:00
|
|
|
} catch (err) {
|
2018-09-24 12:59:47 +00:00
|
|
|
// This fails in Firefox with `file:///` URLs :(
|
2018-11-08 06:48:01 +00:00
|
|
|
// Todo: This could use a generic alert library instead
|
|
|
|
alert('Data URL conversion failed: ' + err); // eslint-disable-line no-alert
|
2018-05-18 03:25:45 +00:00
|
|
|
data = '';
|
2018-05-18 04:54:31 +00:00
|
|
|
}
|
2018-05-18 03:25:45 +00:00
|
|
|
post({href, data});
|
2018-05-18 04:54:31 +00:00
|
|
|
};
|
|
|
|
img.src = href;
|
|
|
|
} else {
|
|
|
|
// Do ajax request for image's href value
|
|
|
|
$.get(href, function (data) {
|
2018-05-18 03:25:45 +00:00
|
|
|
post({href, data});
|
2018-05-18 04:54:31 +00:00
|
|
|
}, 'html'); // 'html' is necessary to keep returned data as a string
|
|
|
|
}
|
|
|
|
return false;
|
2018-05-16 00:53:27 +00:00
|
|
|
});
|