Karol Haliński
Karol Haliński

Reputation: 140

Let the User download the CSS file for iframe element

I am using two following JS functions to do the following steps: Get iFrame html content generated via user interaction into a string THEN Get the CSS stylesheet contained on my server named "myStylesheet.css" into a string THEN Download those files to the reguesting user

var iframe = document.getElementById('frame');

function downloadFile(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);

if (document.createEvent) {
    var event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true);
    pom.dispatchEvent(event);
}
else {
    pom.click();
}
//example : downloadFile("hello.txt", "Hello World!") or for custom name filedownloadFile(myPageName +'.html', iFrameContent)
}

function publishWebsite(){
var htmlCodeForFrame = document.getElementById('frame').contentWindow.document.body.innerHTML;
var ccsCodeForFrame = "";
downloadFile("myWebsite.html", htmlCodeForFrame); //save html of frame into a file and download it to user
downloadFile("myStylesheet.css", ccsCodeForFrame); //save css of frame into a file and download it to user
}

My problem lies in turning a CSS stylesheet into a variable then download it (I want to stick with my download function for clarity because this is a Team Project and it's used in many other places.) to user. I wish this to be done in Javascript.

Upvotes: 0

Views: 492

Answers (2)

Karol Haliński
Karol Haliński

Reputation: 140

I found myself using the following after some tinkering:

 <iframe id="cssFrame" src="myStylesheet.css"  style="display: none;"></iframe>

With conjunction of my code from the first post, I saved the content of the iframe to a string and saved the string in a file with .css extension. Works good.

Upvotes: 0

Robin B
Robin B

Reputation: 680

For modern browsers you could use the download-tag

<a href="{your url}" download="{file name}">Download</a>

N.B: the file name is not required

(see browser support)

One other (rather nasty) trick is to create an ajax request with an invalid MIME-type, this prompts the browser to download the file since it can't render the view. Or you could use the application/octet-stream MIME-type.

Upvotes: 1

Related Questions