javascript - 如何在 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>
解决方案
我相信您对范围界定有疑问,您需要在“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();
}
推荐阅读
- android - 改造 Gson 序列化在三星 S9 设备上无法正常工作
- python - 从字典关键字创建变量
- r - 从 UTF-8 字符串中删除不可见字符
- firebase - Ionic 3 Firebase Google Auth 重定向到本地主机而不是应用程序
- azure-pipelines - 如何强行使我的天蓝色管道 CI/CD 失败
- flutter - Flutter 网络图像作为谷歌地图标记
- python - 在情节子图中更改单轴
- python - python无法打开具有读写能力的文件
- java - 对于 PersonRepository 类型,方法 findOne(Long) 未定义
- java - android.os.FileUriExposedException:在 android.os.StrictMode.onFileUriExposed