Monday, November 10, 2008

Save to local files with XPCOM for Selenium Firefox Chrome

We save selenium run snapshot/result/log to local files instead of complex POST to server solution. We require APIs in browser(out of Security Sandbox) for local files accessing.

In IEHTA, there is ActiveX object FSO to access local files.
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
Is there a similar object in Mozilla Firefox Chrome?
The answer is XPCOM object @mozilla.org/file/local;1

Save to file Sample:
function saveFile(fileName, val){
   try {
      netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   } catch (e) {
      //alert("Permission to save file was denied.");
   }
   var file = Components.classes["@mozilla.org/file/local;1"]
             .createInstance(Components.interfaces.nsILocalFile);
   file.initWithPath(fileName);
   if (file.exists() == false) {
     //alert("Creating file... " );
     file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
   }
   var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
            .createInstance(Components.interfaces.nsIFileOutputStream);
   outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 ); 
   //UTF-8 convert
   var uc = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
     .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
   uc.charset = "UTF-8";
   var data_stream = uc.ConvertFromUnicode(val);
   var result = outputStream.write(data_stream, data_stream.length );
   outputStream.close(); 
}
We use UTF-8 encode here.

No comments:

Post a Comment