2

I have a website in which I am using my chat website as in iframe as follows,

<iframe id="chat-iframe" src="https://chat/livechat" style="width: 100%; height: 100%; border: none; background-color: transparent; display: initial;"></iframe>

I have a download file button inside the iframe as follows,

<a target="_blank" rel="noopener noreferrer" class="file-attachment__inner__mQCxr" style="cursor:pointer" href="https://chat.com/file-upload/4aNPtgsok63sfdMLr/YN_Hotel_F07-010-F6F9%20(2)%20(1)%20(9)%20(27)%20(11).pdf')">

picture

When I click on the anchor tag, it is opening the pdf in the same window of iframe instead of downloading. Can anyoneplease hlep me out sorting it. Thanks.

I even added tried downloading via JS code but still opening in the same tab,

function onClickFileDownload(link) {
  const anchor = document.createElement("a");
  anchor.href = link;
  anchor.download = 'test';
  anchor.target = '_blank';
  document.body.appendChild(anchor);
  anchor.click();
  document.body.removeChild(anchor);
}
klp
  • 21
  • 3
  • Seems you missed the `sandbox` attribute in your `iframe` tag: https://stackoverflow.com/a/64382081/188331 – Raptor Oct 27 '22 at 09:00
  • I added '' but says the following error DOMException: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag. – klp Oct 27 '22 at 09:32
  • Added the sandbox attribute but still opening in the same tab. – klp Oct 27 '22 at 09:40
  • Yes, the `iframe` URL requires to be the same origin in order for JS to work. – Raptor Oct 28 '22 at 01:59

1 Answers1

1

you could just use the HTML5 download attribute. E.G download or if you need the javascript engine to do it.

let fileHref = baseLocation + '/excelexports/' + fileName;
var anchor = document.createElement('a');
anchor.setAttribute("download", true);
anchor.setAttribute("href", fileHref);
anchor.click();

If your using a click to run this javascript you can even pass though the event to help identify your download as a user action to more intrusive popup blockers.

someElem.addEventListener('click', function(evt){
    let fileHref = baseLocation + '/excelexports/' + fileName;
    var anchor = document.createElement('a');
    anchor.setAttribute("download", true);
    anchor.setAttribute("href", fileHref);
    anchor.dispatchEvent(evt);
});

source: https://www.w3schools.com/tags/att_a_download.asp

Raptor
  • 53,206
  • 45
  • 230
  • 366
  • 1
    @Delno I tried the similar way , updated my question but even that opening the file in iframe . – klp Oct 27 '22 at 08:53
  • don't quote w3schools please. Try MDN: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download – Raptor Oct 27 '22 at 08:56