node-webkit using window.open() to download a file open another window - javascript

I'm currently porting a nodejs / angular webapp to Windows using nodewebkit. Everything has been working pretty well for now but I'm facing a litle problem when I want the user to download a file.
In order to start the download with the save file Dialog, I use a simple window.open(url) where url can be a link to any kind of files. This line actually do it's job and pop the window dialog for saving a file, but at the same time, a blank node-webkit page appears.
I've been trying to mess around with node-webkit for a while without managing to remove this blank page.
As anyone experienced the same kind of behavior ?
I'll be interested in any lead, I'm not into the js stuff for long so I may have missed something obviouvs.
Have a nice wathever time of the day it is where you live !

a more better solution is found here
Step 1 In your html file, add a Input tag block like below:
<input id="export_file" type="file" nwsaveas style="display:none" nwworkingdir=""/>
Step 2 Add a new function in your javascript file like below:
function saveFile(name,data) {
var chooser = document.querySelector(name);
chooser.addEventListener("change", function(evt) {
console.log(this.value); // get your file name
var fs = require('fs');// save it now
fs.writeFile(this.value, data, function(err) {
if(err) {
alert("error"+err);
}
});
}, false);
chooser.click();
}
Step 3 Save your file where ever you like by using saveFile(name,data) function like below:
...
_exportCSV="you data to save";
saveFile('#export_file',_exportCSV);
...

As questioner said to be working:
location.href = url
Is the correct usage.

Related

Automate image upload with Selenium but without AutoIt

I have a non-traditional, image upload button on my company's website. I want to have an automated way to upload an image using this button, but without having to use a tool like AutoIt in order to interact with the file explorer.
Here's a sample of this button's HTML:
<button ng-click="onClick()" ng-disabled="readOnly" accepted-types="image/*" on-files-selected="onFilesSelected" allow-multiple="true" readonly="readonly">Add images</button>
It's a bit different than the usual input element, e.g. <input type="file">, and it's using AngularJS. Since it's not an input element, I don't think I can use Selenium's sendKeys() function to input the image's file location on my machine.
Is there any hack or workaround to uploading the image? I was considering things like overwriting the onClick() function to do read from a specified location (this approach doesn't really seem like it's doable), or possibly intercepting the event that opens the file explorer and trying to hack my way from there, but these are all just unsupported and untested approaches to solving the problem.
Would it be possible to do this in another browser-automation tool, like Microsoft's Playwright?
Use JACOB it provides java native interface where you can use AutoIt functionalities with selenium here is a sample I am using it in most of the places like MSTeams,Slack for Automation[Upload Feature] it does the job.
List of Steps you need to do before jumping to the code:
Step 1:
Download JACOB jar
Step 2:
Register the AutoIt COM libraries e.g regsvr32 AutoItX3_x64.dll
Use these in your code
jacob.jar
AutoItX4Java.jar
jacob-1.18-x64.dll
jacob-1.18-x86.dll
Sample Code:
[This Code Interacts with file explorer]
import com.jacob.com.LibraryLoader;
import autoitx4java.AutoItX;
public class Attachments {
public void uploadAttachments(){
File f = new File("Location");
File[] fil =f.listFiles();
//Upload Button Xpath
WebElement uploadFromComp = driver.findElement(By.xpath("//span[contains(text(),'Upload from my computer')]"));
uploadFromComp.click();
Thread.sleep(5000);
String jacobDllVersionToUse;
if (jvmBitVersion().contains("32")) {
jacobDllVersionToUse = "jacob-1.19-x86.dll";
} else {
jacobDllVersionToUse = "jacob-1.19-x64.dll";
}
File file1 = new File("registerAutoItDll", jacobDllVersionToUse);
System.setProperty(LibraryLoader.JACOB_DLL_PATH, file1.getAbsolutePath());
AutoItX x = new AutoItX();
x.winWaitActive("Open");
x.sleep(5000);
x.send(fil[j].getAbsolutePath());
x.send("{ENTER}", false);
}}
I hope it works for you.
It is 100% posible with playwright and it is lot simplier then in the Selenium.
// Select one file
await page.setInputFiles('input#upload', 'myfile.pdf');
// Select multiple files
await page.setInputFiles('input#upload', ['file1.txt', 'file2.txt']);
See more on:
https://playwright.dev/docs/input#upload-files

set file attribute filesystemobject javascript

I have created a file as part of a script on a network drive and i am trying to make it hidden so that if the script is run again it should be able to see the file and act on the information contained within it but i am having trouble doing this. what i have so far is:
function doesRegisterExist(oFs, Date, newFolder) {
dbEcho("doesRegisterExist() triggered");
sExpectedRegisterFile = newFolder+"\\Register.txt"
if(oFs.FileExists(sExpectedRegisterFile)==false){
newFile = oFs.OpenTextFile(sExpectedRegisterFile,8,true)
newFile.close()
newReg = oFs.GetFile(sExpectedRegisterFile)
dbEcho(newReg.Attributes)
newReg.Attributes = newReg.Attributes+2
}
}
Windows Script Host does not actually produce an error here and the script runs throgh to competion. the only guides i have found online i have been attempting to translate from VBscript with limited success.
variables passed to this function are roughly declared as such
var oFs = new ActiveXObject("Scripting.FileSystemObject")
var Date = "29-12-2017"
var newFolder = "\\\\File-Server\\path\\to\\folder"
I know ActiveX is a dirty word to a lot of people and i should be shot for even thinking about using it but it really is a perfect fit for what i am trying to do.
Please help.
sExpectedRegisterFolder resolves to \\\\File-Server\\path\\to\\folder\\Register which is a folder and not a file.
I get an Error: file not found when I wrap the code into a try/catch block.
I tested the code on a text file as well, and there it works.
So you're either using the wrong method if you want to set the folder to hidden.
Or you forgot to include the path to the text if you want to change a file to hidden.
( Edit: Or if Register is the name of the file, add the filetype .txt ? )
If you change GetFile to GetFolder as described in https://msdn.microsoft.com/en-us/library/6tkce7xa(v=vs.84).aspx
the folder will get hidden correctly.

Create file to download js

I'm receiving a JSON output from an API, and i want to use it with JS and also save that output to file. Is there any way to trigger the browser download machanism using JS with thet output?
Maybe now some browsers support the attribute download but you don't trigger the browser to automatically download the file.
the only way i know is #BAS's solution but without a filename.
tested in chrome ..
array=[{a:'1',b:'2'},{x:'3',y:'4'}];
function dl(array,filename){
var b=document.createElement('a');
b.download=filename;
b.textContent=filename;
b.href='data:application/json;base64,'+
window.btoa(unescape(encodeURIComponent(JSON.stringify(array))))
// or
// b.href='data:application/javascript;charset=utf-8,'+JSON.stringify(json);
return b
}
document.body.appendChild(dl(array,'my.json'));
example
http://jsfiddle.net/8yQcW/
UPDATE direct download works ... on chrome i tested.
on append simulate click
var e=document.createEvent('Events');
e.initEvent('click',true,false);
document.getElementById('dl').dispatchEvent(e);
http://jsfiddle.net/8yQcW/1/
You could try it with a data URI:
function triggerDownload(json) {
var dataUri = 'data:text;charset=utf-8,' + json;
window.open(dataUri);
}
Try entering data:text;charset=utf-8,{"Key":"Value"} into your browsers address bar. It should show you the save dialog.
See here for more information and browser support.

Cannot find file in the gallerie after downloading it with PhoneGap in Android

i have a problem with the the downloaded files in my PhoneGap-App for Android.
The download-Function from PhoneGap actually works quite well i think. It gets the file from the URL and
stores it on the SD-Card. (Code is below)
So where is the Problem? When I download a JPG or PNG to the
Download-folder, i want it be accessible through the native Gallery.
But the picture donĀ“t appear in the gallerie. To see it I have to
restart the phone or I have to use another App like Astro.
Is there a "Refresh_the_native_Gallerie"-Function or something like that?
Thank you very much.
try {
var filePath = 'file:///mnt/sdcard/Download/google.png'; // Correct filePath
var url = "https://www.google.de/images/srpr/logo3w.png"; //Correct URL
var fileTransfer = new FileTransfer();
fileTransfer.download(url, filePath, function(entry) {
console.log("s3_download download complete: " + entry.
// Do i need a "Refresh_all_other_Apps"-function here?
}, function(error) {
// Normally no Error
console.log("s3_download download error source " + error.source);
console.log("s3_download download error target " + error.target);
console.log("s3_download download error code" + error.code);
});
} catch (e) {
console.log("downloadTest ERROR: " + e);
}
Cannot answer my own question so fast only edit my question. So here is the answer:
I wrote a little PhoneGap-Plugin, which does actually nothing more than calling the code from zapl. Thanks again. Hope it will help someone with the same problem.
You can find the code here: https://github.com/philipp-at-greenqloud/pluginRefreshMedia
I don't know if that helps you in PhoneGap / JavaScript context:
Your problem is that the gallery will only display files that are indexed in the device media-database. Just adding a file to the file system will not automatically add it to that database. And pretty much the only time a rescan / update of that database happens is when you reboot the device or remount the sdcard (after it was shared with a PC or in case you ejected it and put it back in).
To have a file added to the database the simplest way to to that is to send Intent#ACTION_MEDIA_SCANNER_SCAN_FILE to the MediaScanner to let it add your file to the database. Once that is done the file will show up in the gallery.
Java code for that would be
File newImage = new File("/mnt/sdcard/Download/google.png");
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(newImage));
sendBroadcast(scanIntent);
I wrote a little PhoneGap-Plugin, which does actually nothing more than calling the code from zapl. Thanks again.
Hope it will help someone with the same problem.
You can find the code here: https://github.com/philipp-at-greenqloud/pluginRefreshMedia
This is a well needed plugin. I have been trying to do work arounds for this issue and the plugin works a treat. I was looking at developing one myself, but you have done a great job. My headaches are now subsiding. This works for me.

Is there a way to AutoFormat (Javascript) code in TestComplete?

So similar to ALt-Shift-F in Netbeans, is there a to do this right in the ide in TestComplete? Not sure if this is possible or if anyone can think of a workaround to autoFormat without leaving the TestComplete window.
I'm trying to get the below solution to work with http://jsbeautifier.org/ for javascript / Jscript code in TestComplete.
Thanks
Great question!
There is no built-in function for that. So, we should not expect any solution to be 100% convenient - it is just not a simple task to modify the current script editor contents (if at all possible). So, whatever you do, it will still be some kind of compromise.
In general, the task is three-fold:
Get the current unit code.
Format the code.
Put the code back to the unit.
According to my understanding, items 1 and 3 can be accomplished only by creating a TestComplete plug-in - accessing editors for project nodes is not an easy thing.
UPDATE: silly me! There is a way to access the script editor code - I've updated the below part.
What will help us avoid switching to a different app, are the Script Extensions:
We create a custom Checkpoint in the form of a Script Extension, and install it to TestComplete. As a result, we get a button on the toolbar that we can click to invoke our code.
In the design time action, we call some code that reads the editor contents, then uses external code formatting functionality, and replaces the editor contents with the formatted code.
It would extremely interesting to see the implementations other TestComplete users can suggest! As a start, I am posting a solution that includes using an external web site to format VBScript code (http://www.vbindent.com/). I know that the starter of the post is probably using JScript, but I have not found a JScript formatter yet.
My solution is a simple Script Extension. I can't post a file here, so I will post the code of the two Script Extension files:
Description file:
<!-- Description.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<ScriptExtensionGroup>
<Category Name="Checkpoints">
<ScriptExtension Name="VBScript Code Indent" Author="SmartBear Software" Version="0.1" HomePage="smartbear.com">
<Script Name="VBIndent.js">
<DesignTimeAction Name="Indent Current VBScript Unit" Routine="DesignTimeExecute"/>
</Script>
<Description>
Indents VBScript code in the currently active unit.
</Description>
</ScriptExtension>
</Category>
</ScriptExtensionGroup>
Code file:
// VBIndent.js
function DesignTimeExecute()
{
if (CodeEditor.IsEditorActive)
{
var newCode = IndentVBSCode_Through_VBIndent(CodeEditor.Text);
if (null == newCode)
return;
CodeEditor.Text = newCode;
}
}
function IndentVBSCode_Through_VBIndent(codeToIndent)
{
var URL_VBIndent = "http://www.vbindent.com/?indent";
var httpObj = Sys.OleObject("MSXML2.XMLHTTP");
httpObj.open("POST", URL_VBIndent, false);
httpObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpObj.send("thecode=" + escape(codeToIndent));
var responseText = httpObj.responseText;
// Extract the indented code from the response
var rx = /<textarea name=\"thecode\".*?>((.*\n)*?)<\/textarea>/;
matches = rx.exec(responseText);
if (null == matches)
{
return null;
}
codeIndented = matches[1];
return codeIndented;
}
After you create these files, and put them to something like "\Bin\Extensions\ScriptExtensions\VBIndent", and click "File | Install Script Extensions | Reload", you will see a new "Indent Current VBScript Unit" item in the custom checkpoints drop-down button on the Tools toolbar. Clicking the element will format the VBScript code in the currently active editor.
So, this is to give a clear idea of what a solution can look like. Better suggestions are welcome! Share your thoughts!
FYI
I've done. Based on your posts.
JSFormat.tcx
https://drive.google.com/uc?export=download&id=0B1x_73bHRc2Jcm8wbTJ2dUpZQTQ
To install the extension copy attached file JSFormat.tcx to C:\Program Files (x86)\SmartBear\TestComplete 10\Bin\Extensions\ScriptExtensions
To use view next image:
https://drive.google.com/uc?export=download&id=0B1x_73bHRc2Jc3RuLXFpTnlCSnc
Regards

Categories

Resources