How can i add Libraries to Browser Console? - browser

Can i add any library such as mongoose, to my browser console (even if it is temporary and gets finished on refreshing). So that i could access its function from browser console. Any plugins is also appreciated.

You could add the script tag in the page that has been loaded from browser console by
document.head.innerHTML+="<script src='https://raw.githubusercontent.com/Automattic/mongoose/master/bin/mongoose.js'></script>";
And for more native way,
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://raw.githubusercontent.com/Automattic/mongoose/master/bin/mongoose.js'; // url of the mongoose.js
document.head.appendChild(script);
It will be available in console using
>> mongoose;
<- Object { Error: MongooseError(), Schema: Schema(), Types: Object, VirtualType: VirtualType(), SchemaType: SchemaType(), utils: Object, Document: Document() }

Related

How to download a CSV file with selenium while bypassing the file dialog

I have been trying to access a url with a CSV file to download it in a specific directory, using the Selenium Webdriver for Firefox(geckodriver), in a NodeJS enviroment on Linux-Mint.
This is my code:
const {Builder} = require('selenium-webdriver');
const firefox = require('selenium-webdriver/firefox');
const path = require('path');
const options = new firefox.Options();
options.setPreference('browser.download.dir', path.resolve(__dirname));
options.setPreference('browser.download.folderList', 2);
options.setPreference('browser.helperApps.neverAsk.saveToDisk', 'application/x-csv');
function example(){
let driver = new Builder().forBrowser('firefox').setFirefoxOptions(options).build();
driver.get('http://insight.dev.schoolwires.com/HelpAssets/C2Assets/C2Files/C2ImportCalEventSample.csv');
}
example();
As you can see, I am correctly setting the browser option to browser.helperApps.neverAsk.saveToDisk, so as to be able to bypass the dialog. However, I am still getting the dialog no matter what I do. I haven't tried this code on Windows, but for my purposes it needs to work on Linux.
Am I missing something? Some preference that needs to be added or changed? Or does this not work on my current enviroment?
Thank you in advance for any help provided.
If you are just downloading a file from link why do you need selenium?
A much simple approach will be just to get the file by http and save to file.
const http = require('http');
const fs = require('fs');
const file = fs.createWriteStream("C2ImportCalEventSample.csv");
const request = http.get("http://insight.dev.schoolwires.com/HelpAssets/C2Assets/C2Files/C2ImportCalEventSample.csv", function(response) {
response.pipe(file);
});
If you have to use selenium let me know in the comments and i will try to find a solution for your problem using selenium.

XSLTProcessor is not defined in node.js

I am trying to transform XML to XHTML. I have used XSLTProcessor in client side (Angular) and it's working fine. Now I am trying to use the same code in Node JS but it's not working and I am getting error message as XSLTProcessor undefined. Below is the client side code. Please suggest me the methods available for transformation in Node JS side.
transformXml(xml, xsl) {
var html;
if (this.isIE) {
html = xml.transformNode(xsl);
} else {
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
var xmlDom = xsltProcessor.transformToDocument(xml);
var serializer = new XMLSerializer();
html = serializer.serializeToString(xmlDom.documentElement);
}
return html;
}
XMLTProcessor() is not part of Node.js. You need a package like https://www.npmjs.com/package/xslt or similar - there are a number of packages for XSLT: https://www.npmjs.com/search?q=xslt.

Handle alerts in selenium webdriver for nodejs

I am running a simple webserver in nodejs. On the server side i want to check if the user was successful in getting an alert box in the UI. Could be (confirm , prompt etc) . The payload is in the URL. To check this i create a URL and pass it to selenium to check if it creates an alert box. However, all my attempts to handle the alert are failing with an exception. Heres my code
/* global */
const webdriver = require('selenium-webdriver')
const chrome = require('selenium-webdriver/chrome')
var options = new chrome.Options();
options.addArguments('headless');
var path = require('chromedriver').path;
let driver = new webdriver.Builder().
withCapabilities({'browserName': 'chrome', 'alertBehavior': 'IGNORE'}).
setChromeOptions(options).
build();
/* do bunch of stuff */
function checkXSS(payload) {
console.log('checking payload')
var url = 'http://<url>?payload=' + payload
driver.get(url). //exception thrown here itself.
driver.switchTo().alert().then(function() {
driver.switchTo().alert().accept();},
function(){});
}
And i get the below exception
UnexpectedAlertOpenError: unexpected alert open: {Alert text : XSS}
I tried other ways too that were suggested on stackoverflow. Such as using driver.get.then(_, =>), alert.dismiss() etc however all of them still throw the same exception. What am i missing here?

Server Side rendering in mongo with dust

Is it possible to fetch data from MongoDB and render a html template on the server side itself for a node-js project?
As of now in my serverside js file I've done the following.
//Failing array will be populated by a db.find later on.
var failing = [
{ name: "Pop" },
{ name: "BOB" }
];
/*Now i have to send a mail from the server for which I'm using nodemailer.
Where do i store the template ? This is what I've done in the same file */
var template = "<body>{#failing} <p>{.name}</p> {/failing}</body>"
// Add this as the body of the mail and send it.
I'm not sure how to render the data and how to get it displayed. I'm aware storing the template in the variable isn't right but I'm not sure what else to do.
If your template is that short, you can store it in a variable without problem. Obviously, you can store it in a file also.
Let's say you decide to store it in a file index.dust:
<body>{#failing} <p>{.name}</p> {/failing}</body>
Now, in your node controller you need to load the file and generate the html content from it:
const fs = require('fs');
const dust = require('dustjs-linkedin');
// Read the template
var src = fs.readFileSync('<rest_of_path>/index.dust', 'utf8');
// Compile and load it. Note that we give it the index name.
var compiled = dust.compile(src, 'index');
dust.loadSource(compiled);
// Render the template with the context. Take into account that this is
// an async function
dust.render('index', { failing: failing }, function(err, html) {
// In html you have the generated html.
console.log(html);
});
Check the documentation in order not to have to compile the template every time you have to use it.

Passing objects between nodejs and jade

I have the following code in my server.js
var cddata = [];
body.rows.forEach(function(doc) {
cddata.push([{id: doc.id, name: doc.key, text:doc.value.Time, group: 1}]);
});
response.render('timeline', {cddata: JSON.stringify(cddata)});
and I have the following in my Jade view file
script(src='vis/dist/vis.js')
link(rel="stylesheet", href="vis/dist/vis.css", type="text/css")
script.
//alert(cddata);
var options = {};
var data = new vis.DataSet(cddata);
var container = document.getElementById('visualization');
new vis.Timeline(container, data, options);
However, nothing related to the chart is rendered. I presume the object is not correctly passed to the jade file. Please help!
Also, is there a way to verify the incoming object in Jade? Alerts dont seem to work.
thanks
The <script> in your jade is a browser side script so won't be able to access variables in the templates generation scope. You'll need to output your data as JSON and read it in using browser side JavaScript, something like this:
script(src='vis/dist/vis.js')
link(rel="stylesheet", href="vis/dist/vis.css", type="text/css")
script.
var chartData = JSON.parse('#{cddata}')
var options = {};
var data = new vis.DataSet(chartData);
var container = document.getElementById('visualization');
new vis.Timeline(container, data, options);
After much deliberation, the following worked to pass object from node server to client side server scripting on Jade file.
on the server.js, where dbdata is an array of JSON objects
response.render('timeline', {dbdata:dbdata});
On the jade file,
script.
var chartData = !{JSON.stringify(dbdata)};
Thanks,

Resources