tags:

views:

635

answers:

2

document.execCommand('SaveAs', false,'fileName' + ".txt");

I am trying to save the page in a file by using the above command in javascript.

Issue: I have some hidden elements on the page..CSS Style [display:none], So when I try to save the pages content using the above command, it writes the hidden elements contents as well.

Any ideas how to get rid of the hidden elements content. Is there any other parameter that we can pass which will tell not to save the hidden elements content.,

Any help is appreciated.

PS: I dont want to remove the hidden elements content from DOM. Its not an option.

Thanks, Ben

Does anyone has any other answers..

A: 

Untested... but my only thought would be to:

  • wrap the call...
  • save a variable with a "pure" copy of the entire DOM...
  • strip out the hidden elements e.g. removeChild() where the display:none is set
  • execute the save
  • reset the DOM to the original

But that seems like a fair bit of work... what is the reason to "remove" this hidden content? maybe there is a better solution we can offer?

e.g. if this is for "security" to ensure users don't see stuff they shouldn't, then this is a bad approach... better off not to render the content in the first place.

scunliffe
good user experience. Ideally user should save what is shown on the page, not the hidden content.Its a valid scenario.
Ben
+1  A: 

Here's what I came up with

Clone the document, then remove all nodes with the class name which specifies it as hidden, or as content that you don't want saved. In my case I used the class name 'hidden'. removeElementsByClass goes through the cloned document and removes all the bad nodes. Now run the exec on the object newDoc, saving this cloned and reduced document.

var newDoc = document.getElementsByTagName("html")[0].cloneNode(true);
removeElementsByClass(newDoc, 'hidden');
newDoc.execCommand('SaveAs', false,'fileName' + ".txt");

function removeElementsByClass(object, class)
{
    var elementArray  = [];
    if (object.all)
    {
     elementArray = object.all;
    }
    else
    {
     elementArray = object.getElementsByTagName("*");
    }

    var matchedArray = [];
    var pattern = new RegExp("(^| )" + class + "( |$)");

    for (var i = 0; i < elementArray.length; i++)
    {
     if (pattern.test(elementArray[i].className))
     {
             elementArray[i].parentNode.removeChild(elementArray[i]);
     }
    }
}
Ian Elliott