Search code examples
javascriptnode-webkitnw.js

How to programmatically upload file in node-webkit / nw.js


I am using node-webkit/nw.js as an automation tool to test my web application. My application has a record mode to capture all click events and keyboard events. All the captured events are logged into a file and while in play mode, the logged events are run from clean state.

However, since file uploads open up a File dialog, I cannot emulate a file selection. Since am using node webkit, I can programmatically read a file from the user system and upload it as blob using FormData and Blob . However, based on the file upload, there are events that have to be triggered, and after the upload is complete other fields have to populated say with an image.

Is there a way I can attach a file in the form data programmatically? I can understand it is not possible in a normal browser since it would be a security issue. In a node webkit environment am anyways able to access and upload user file in the background. So, will it be possible to modify the input file value or by some other means add a blob inside the Form and upload the file?


Solution

  • It seems the steps involved is elaborated in the github page of nw.js but not on docs.

    Steps to get reference of form node and input node.

    //Detect if button clicked is inside a form. 
    //In my case all attachments use same component. So I know the no. of levels to move up
    if(activeElm.parentNode.parentNode.parentNode.tagName=="FORM"){
        //Navigate to input elm and save it as new activeElm. 
        //Navigation will differ based on your page.
        activeElm = activeElm.parentNode.parentNode.parentNode.getElementsByTagName('input')[0];
    }
    

    Steps to emulate file attachment.

    var f = new File('/path/to/file', 'name');
     var files = new FileList();
     files.append(f);
     elm.files = files;