如何将 window.onload 中的函数输出传递给另一个 javascript 文件?

How can I pass a function output that's inside of window.onload to another javascript file?

在第一页上有一个按钮,单击该按钮会打开第二页,您可以在 canvas 上画图。绘制完所述图片后,您可以单击将 canvas 转换为图像 URL 并关闭第二页 window.

的发布按钮

然后我希望图像自动显示在原始首页上。

问题是,我似乎无法将新图像 URL 输出传回第一页。这两个脚本都包含在 window.onload 中,这似乎不允许我全局访问变量或函数。我已经尝试将 pubNow 函数放在 canvas 之外,将 canvas 转换为图像,但将代码放在范围之外,并且几个变量 return 未定义。我怎样才能传递这个变量?

下面是代码。请仅香草Javascript。

注意:每个页面都有自己的 HTML、CSS 和 JS 文件。我想将函数的输出从一个 JS 文件传递​​到另一个 JS 文件。

//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();
}
}

您可以使用 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>

Demo