Creating a downloadable text-file using blobs

Created as part of my answer to http://stackoverflow.com/questions/8178825/create-text-file-in-javascript

by nirus

HTML

<span class="title-link__title-text">Benefit plan 'could hit young Britons'</span>

<div>
    <iframe id="frame" src="http://www.bbc.co.uk/news"></iframe>
</div>
<button id="create">Download</button>

JavaScript

(function () {
    var textFile = null,
        makeTextFile = function (text) {
            var data = new Blob([text], {
                type: 'text/plain'
            });

            // If we are replacing a previously generated file we need to
            // manually revoke the object URL to avoid memory leaks.
            if (textFile !== null) {
                window.URL.revokeObjectURL(textFile);
            }

            textFile = window.URL.createObjectURL(data);

            return textFile;
        };
  
    var iframe = document.getElementById('frame');    
    var commFunc = function () {
            var iframe2 = document.getElementById('frame'); //This is required to get the fresh updated DOM
            var innerDoc = iframe2.contentDocument || iframe2.contentWindow.document;            
            var getAll = Array.prototype.slice.call(innerDoc.querySelectorAll(".title-link span"));          
            var dummy = "";
            for (var obj in getAll) {
                dummy = dummy.concat("\n" + (getAll[obj]).innerText);
            }
            var link = document.createElement("a");
            link.href = makeTextFile(dummy);
            link.download = "sample.txt"
            link.click();
            console.log("Downloaded the sample.txt file");
        };
    
    iframe.onload = function () {
        setTimeout(commFunc, 1000); //Adjust the time required to load
        //setInterval(commFunc, 1000);
    };  
    
    //Click the button when the page inside the iframe is loaded
    create.addEventListener('click', commFunc);            
})();