I am trying to write a Tampermonkey userscript that uses a <canvas>
to combine pictures into a single image and then auto downloads it.
My script code:
// ==UserScript==
// @name Picture Download
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Picture Download
// @author Oray
// @match https://www.example.com/*
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js
// @grant unsafeWindow
// ==/UserScript==
(function(){
function GM_wait(){
if(typeof unsafeWindow.jQuery == 'undefined'){
window.setTimeout(GM_wait,100);
}else{
unsafeWindow.jQuery(function() { letsJQuery(unsafeWindow.jQuery); });
}}
GM_wait();
function letsJQuery($){
$('html[lang] > body').prepend('<canvas id="cve"></canvas>');
var img1 = new Image();
var img2 = new Image();
var combined = new Image();
var nloaded = 0;
var combinedx;
var filename;
var e;
function checkload(event){
nloaded++;
if (nloaded < 2){
return;
}
var canvas = document.getElementById('cve');
var context = canvas.getContext('2d');
canvas.width = img1.width;
canvas.height = img1.height + img2.height;
context.drawImage(img1, 0, 0);
context.drawImage(img2, img1.width / 2 - img2.width / 2 , img1.height);
combinedx = canvas.toDataURL('data/gif');
filename = 'myimage.png';
var lnk = document.createElement('a');
lnk.download = filename;
lnk.href = combinedx;
e = document.createEvent("MouseEvents");
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false,false, 0, null);
lnk.dispatchEvent(e);
}
img1.onload = checkload;
img1.crossOrigin = "Anonymous";
img1.src ="https://images-na.ssl-images-amazon.com/images/I/81pNr82OTgL._SX679_.jpg";
img2.onload = checkload;
img2.crossOrigin = "Anonymous";
img2.src = "https://images-na.ssl-images-amazon.com/images/I/31W%2BDml7GsL.jpg";
}
})();
...works in the console but doesn't as a Tampermonkey script.
Why?
Editor's note: By the original title, this would be a very common problem due to AJAX timing (example). But this question covers a different, rarer cause with the same base symptom.