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

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

SAPUI5: Open JSON in new browser window fails

问题

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

  1. const uri = `data:text/json,${sJSONContent}`;
  2. 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:

  1. const uri = `data:text/json,${sJSONContent}`;
  2. 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

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

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

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

英文:

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

  1. // it is important to use the "data:" prefix and urlencode the data if necessary!
  2. const sData = `data:text/json;charset=utf-8,${sJSONContent}`;
  3. // create a HTML 'anchor' element
  4. const dummyAnchor = document.createElement('a');
  5. // add the data string as 'target' of that anchor
  6. dummyAnchor.setAttribute('href', sData);
  7. // set the 'download' attribute so that the browser treats the href as to be downloaded
  8. dummyAnchor.setAttribute('download', 'my.json');
  9. // add the dummyAnchor element to the document
  10. document.body.appendChild(dummyAnchor);
  11. // trigger clicking of that anchor element to start the download
  12. dummyAnchor.click();
  13. // remove the dummy again from the document to avoid side effects
  14. 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:

确定