How to use XPCOM in iMacros to load data and write data

250 Views Asked by At

These are the functions which load file and write file. I used JavaScript and XPCOM for these operations. You can use these functions in iMacros JavaScript file.

Edit: These functions work best in iMacros version 8.9.7 and corresponding Firefox. The later versions of iMacros addon don't support JavaScript. Also it's best to use Firefox 47 with disabled updates. And you can use latest Pale Moon browser with addon 8.9.7 . If there is a content in file the WriteFile function simply adds data in new line.

//This function load content of the file from a location
//Example: LoadFile("C:\\test\\test.txt")

function LoadFile(path) {

    try {
        Components.utils.import("resource://gre/modules/FileUtils.jsm");

        var file = new FileUtils.File(path);

        file.initWithPath(path);
        var charset = 'UTF8';
        var fileStream = Components.classes['@mozilla.org/network/file-input-stream;1']
            .createInstance(Components.interfaces.nsIFileInputStream);
        fileStream.init(file, 1, 0, false);
        var converterStream = Components.classes['@mozilla.org/intl/converter-input-stream;1']
            .createInstance(Components.interfaces.nsIConverterInputStream);
        converterStream.init(fileStream, charset, fileStream.available(),
            converterStream.DEFAULT_REPLACEMENT_CHARACTER);
        var out = {};
        converterStream.readString(fileStream.available(), out);
        var fileContents = out.value;
        converterStream.close();
        fileStream.close();

        return fileContents;
    } catch (e) {
        alert("Error " + e + "\nPath" + path)
    }

}

//This function writes string into a file

function WriteFile(path, string) {
    try {
        //import FileUtils.jsm
        Components.utils.import("resource://gre/modules/FileUtils.jsm");
        //declare file
        var file = new FileUtils.File(path);

        //declare file path
        file.initWithPath(path);

        //if it exists move on if not create it
        if (!file.exists()) {
            file.create(file.NORMAL_FILE_TYPE, 0666);
        }

        var charset = 'UTF8';
        var fileStream = Components.classes['@mozilla.org/network/file-output-stream;1']
            .createInstance(Components.interfaces.nsIFileOutputStream);
        fileStream.init(file, 18, 0x200, false);
        var converterStream = Components
            .classes['@mozilla.org/intl/converter-output-stream;1']
            .createInstance(Components.interfaces.nsIConverterOutputStream);
        converterStream.init(fileStream, charset, string.length,
            Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);

        //write file to location
        converterStream.writeString(string + "\r\n");
        converterStream.close();
        fileStream.close();

    } catch (e) {
        alert("Error " + e + "\nPath" + path)
    }

}


//this function removes file from location
function RemoveFile(path) {

    var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    //file.initWithPath("c:\\batstarter6_ff.cmd");
    file.initWithPath(path);

    /*
    var file = IO.newFile(path, name);

     */
    file.remove(false);

}


// Download a file form a url.

function saveFile(url) {

    try {

        // Get file name from url.
        var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = function () {
            var a = document.createElement('a');
            a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
            a.download = filename; // Set the file name.
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            delete a;
        };
        xhr.open('GET', url);
        xhr.send();

    } catch (e) {
        alert("Error " + e)
    }
}


/*
This function runs file from given path
 */

function RunFile(path) {

    var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    //file.initWithPath("c:\\batstarter6_ff.cmd");
    file.initWithPath(path);
    file.launch();

}


//this function downloads a file from url
function downloadFile(httpLoc, path) {
    try {
        //new obj_URI object
        var obj_URI = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(httpLoc, null, null);

        //new file object
        var obj_TargetFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);

        //set file with path
        obj_TargetFile.initWithPath(path);
        //if file doesn't exist, create
        if (!obj_TargetFile.exists()) {
            obj_TargetFile.create(0x00, 0644);
        }

        //new persitence object
        var obj_Persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);

        // with persist flags if desired
        const nsIWBP = Components.interfaces.nsIWebBrowserPersist;
        const flags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
        obj_Persist.persistFlags = flags | nsIWBP.PERSIST_FLAGS_FROM_CACHE;
        /*
        var privacyContext = sourceWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
        .getInterface(Components.interfaces.nsIWebNavigation)
        .QueryInterface(Components.interfaces.nsILoadContext);*/

        //save file to target
        obj_Persist.saveURI(obj_URI, null, null, null, null, obj_TargetFile, null);
    } catch (e) {
        alert(e);
    }
}



//This function prompts user to select file from folder and use it

function PickFile(title) {

    const nsIFilePicker = Components.interfaces.nsIFilePicker;

    var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
    fp.init(window, title, nsIFilePicker.modeOpen);
    fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText);

    var rv = fp.show();
    if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
        var file = fp.file;
        // Get the path as string. Note that you usually won't
        // need to work with the string paths.
        var path = fp.file.path;
        // work with returned nsILocalFile...
        return path;

    }

}

//This function prompts user to select folder from folder and use it
function PickFolder(title) {

    var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
    picker.appendFilters(Components.interfaces.nsIFilePicker.filterAll);
    //folder
    picker.init(window, title, Components.interfaces.nsIFilePicker.modeGetFolder);
    //or file
    // picker.init (window, "Choice file", Components.interfaces.nsIFilePicker.modeOpen);
    if (picker.show() == Components.interfaces.nsIFilePicker.returnOK) {

        return picker.file.path;
    } else {
        return false;
    }
}



//this function offers a set of options to select from
//items is an array of options
//title is the dialog title
//qustion is a question asked to user.

function Select(items, title, question) {

    var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
        .getService(Components.interfaces.nsIPromptService);

    //var items = ["Articles", "Modules", "Both"]; // list items

    var selected = {};

    var result = prompts.select(null, title, question, items.length,
            items, selected);

    // result is true if OK was pressed, false if cancel. selected is the index of the item array
    // that was selected. Get the item using items[selected.value].

    var selected = items[selected.value];

    return selected;

}

Edit: I am also adding iMacros version 8.9.7 addon to download because version 10 doesn't support JavaScript http://download.imacros.net/imacros_for_firefox-8.9.7-fx.xpi

Edit1: I added some more useful functions for iMacros.

0

There are 0 best solutions below