“SAPUI5: 在新浏览器窗口中打开 JSON 失败”

huangapple go评论78阅读模式
英文:

SAPUI5: Open JSON in new browser window fails

问题

我想将JSON从我的应用程序下载到磁盘。为此,我从后端检索编码为字符串的JSON,并使用以下方法:

const uri = `data:text/json,${sJSONContent}`;
sap.m.URLHelper.redirect(uri, true);

这会打开一个新窗口,但什么都没有显示,新窗口的控制台中显示错误信息“不允许导航到数据URL的顶级框架”。

我做错了什么?

谢谢

英文:

I would like to download JSON from my app to disk. For this purpose I am retrieving the JSON as encoded string from the backend and using this approach:

const uri = `data:text/json,${sJSONContent}`;
sap.m.URLHelper.redirect(uri, true);

This opens a new window but nothing is displayed and there is the error "Not allowed to navigate top frame to data URL" displayed in the new window's console.

What am I doing wrong?

Thanks

答案1

得分: 0

好的,以下是翻译好的代码部分:

// 重要的是要使用"data:"前缀,并根据需要对数据进行urlencode!
const sData = `data:text/json;charset=utf-8,${sJSONContent}`;
// 创建一个HTML 'anchor'元素
const dummyAnchor = document.createElement('a');
// 将数据字符串添加为该锚点的 'target'
dummyAnchor.setAttribute('href', sData);
// 设置 'download' 属性,以便浏览器将 href 视为要下载的内容
dummyAnchor.setAttribute('download', 'my.json');
// 将 dummyAnchor 元素添加到文档中
document.body.appendChild(dummyAnchor);
// 触发点击该锚点元素以开始下载
dummyAnchor.click();
// 从文档中移除 dummyAnchor 以避免副作用
dummyAnchor.remove();

希望这对其他人有所帮助!

英文:

OK, I found it out myself. This is how to do it:

// it is important to use the "data:" prefix and urlencode the data if necessary!
const sData = `data:text/json;charset=utf-8,${sJSONContent}`;
// create a HTML 'anchor' element
const dummyAnchor = document.createElement('a');
// add the data string as 'target' of that anchor
dummyAnchor.setAttribute('href', sData);
// set the 'download' attribute so that the browser treats the href as to be downloaded
dummyAnchor.setAttribute('download', 'my.json');
// add the dummyAnchor element to the document
document.body.appendChild(dummyAnchor);
// trigger clicking of that anchor element to start the download
dummyAnchor.click();
// remove the dummy again from the document to avoid side effects
dummyAnchor.remove();

I hope this will help someone else!

huangapple
  • 本文由 发表于 2023年6月29日 18:02:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定