On the first page there is a button that when clicked, opens a second page that allows you to draw a picture on a canvas. Once you've finished drawing said picture, you can click the publish button which transforms the canvas into an image URL and closes the second page window.
I then want the image to be displayed on the original first page automatically.
The problem is, I can't seem to pass the new image URL output back to the first page. Both scripts are wrapped in a window.onload which doesn't seem to allow me to access the variables or functions globally. I've tried putting the pubNow function, that transforms the canvas into an image, outside the window.onload but that puts the code outside the scope and several of the variables return undefined. How can I pass this variable?
Here is the code below. Only vanilla Javascript please.
Note: Each page has its own HTML, CSS, and JS file. I want to pass the output of a function from one JS file to another.
//HTML
<script src= 'file1.js'></script>
<script src= 'file2.js'></script>
//JS File1
window.onload = function(){
//code that needs to use output of pubNow() after publish button is clicked on second page
}
//JS File2
const canvas = document.getElementsByClassName('draw');
const draw = canvas[0].getContext('2d');
//code that allows user to draw
const publish = document.getElementsByClassName('publish');
publish[0].addEventListener('mousedown', pubNow);
publish[0].addEventListener('mousedown', close);
window.onload = function () {
function pubNow (canvas){
const image = new image();
image.src = canvas.toDataURL('image/png');
return image;
}
function close (){
window.close();
}
}
You can do it using postMessage
:
index.html
<button id="open-btn">Open the canvas page</button>
<img id="img" src="" alt="" />
<script>
document.getElementById("open-btn").addEventListener("click", openCanvasPage);
window.addEventListener("message", function(msg) {
document.getElementById("img").setAttribute("src", msg.data);
});
function openCanvasPage() {
open("draw.html");
}
</script>
canvas.html
<canvas id="canvas" width="500" height="500"></canvas>
<button id="publish-btn">Publish</button>
<script>
document.getElementById("publish-btn").addEventListener("click", publishDrawing);
function publishDrawing() {
// `opener` is the window that spawned this one
opener.postMessage(canvas.toDataURL(), "*");
close();
}
</script>