using FileSaver to overcome Lightning tab limitations
Table of contents
I recently resolved a unique task that made me realize the limitations put by Lightning tabs. given below is how I resolved it and
component involved-
Lightning tab (
Visualforce page (VfParent)
Lightning component (LWCChild)
The Visualforce component has the LWC embedded inside it, which in turn is added to an LWC tab.
VfParent code -
<apex:includeLightning />
<script>
$Lightning.use("cpint:LWCChild", function() {
$Lightning.createComponent(
"cpint:LWCChild",
{dummyVal:dumToken},
"ConfigSetting",
function(cmp) {
lwcCmp = cmp;
}); })
</script>
</apex: page>
So basically, this piece of code is embedding the LWCChild inside it and passing some parameters too.
LWCChild -
HTML -
<template>
<lightning-tabset>
<lightning-tab label="Testing the download">
<button onclick={downloadDummyFile}>Download Dummy File</button>
</lightning-tab>
</lightning-tabset>
</template>
Javascript -
downloadDummyFile() {
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
blob = new Blob([(json)], {type: "application/json"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
let data = { key: 'value' };
let fileName = 'This is my custom filename.txt';
saveData(data, fileName);
}
}
This is how it will look on the UI side -
How this is supposed to work -
The functionality is pretty simple, you click on the button and then a file should get downloaded, this works as expected when you open just the VF page in a new window (by clicking on the "open in new tab" button on the VF page record page) and click on download, but when we do the same in the lightning tab, we get this below pop-up.
(yes, I did give all the browser permissions but it didn't seem to work)
Solution -
after a lot of research, the only way to make this work was to try out many third party libraries, The one that worked for me was FileSaver
Import the filesaver library using the loadscript.
send the blob to the saveFile method of this function.
whola ! the file will be downloaded
Subscribe to my newsletter
Read articles from nishant chimote directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
nishant chimote
nishant chimote
I'm a Salesforce developer who has worked on 3 Appexchange applications and on client based Migration project. My work experience involes extensive use of Apex, Apex triggers, LWC, Salesforce admin. Feel free to contact me