首页 > 解决方案 > 如何在 javascript 函数中使用接收到的消息中的变量?

问题描述

这是我的第一个 HTML 网页项目之一。长话短说,我在网页中有一个 iframe,我需要一个按钮来下载用户在网页中创建的 svg。我已经弄清楚了下载部分,我的问题是接收消息并将其传递给下载功能。我已经将下载功能更改为打印,以查看 iframe 是否接收到正确的消息,并且确实如此。但是,当我使用下载功能时,它说接收到的数据没有定义。非常感谢任何帮助

window.onmessage = (event) => {
  if (event.data) {
    let receivedData = event.data;
  }
};

function downloadSVG() {
  let svgData = receivedData;

  /// Create a fake <a> element
  let fakeLink = document.createElement("a");
  /// Add image data as href
  fakeLink.setAttribute('href', 'data:image/svg+xml;base64,' + window.btoa(svgData));
  /// Add download attribute
  fakeLink.setAttribute('download', 'imageName.svg');
  /// Simulate click
  fakeLink.click();

}
<a href="javascript: downloadSVG();">download SVG</a>

标签: javascripthtmlsvg

解决方案


我相信您对范围界定有疑问,您需要在“window.onmessage”处理程序之外声明“receivedData”。像这样在'window.onmessage'之前声明它

let receivedData = null;
window.onmessage = (event) => {
    if (event.data) {
        receivedData = event.data;
    }
};

更新#0

这是您的“a”标签的替代品,使其成为按钮

<button id='downloadSVG' type="button" onclick="downloadSVG()" disabled>download SVG</button>

let receivedData = null;
window.onmessage = (event) => {
  if (event.data) {
    // once the data is received - get the button by ID
    const button = document.querySelector('#downloadSVG')
    // activate the button
    button.disabled = false
    receivedData = event.data;
  }
};

function downloadSVG() {
  let svgData = receivedData; 
  /// Create a fake <a> element
  let fakeLink = document.createElement("a");
  /// Add image data as href
  fakeLink.setAttribute('href', 'data:image/svg+xml;base64,' + window.btoa(svgData));
  /// Add download attribute
  fakeLink.setAttribute('download', 'imageName.svg');
  /// Simulate click
  fakeLink.click();

}

推荐阅读