Nately Jamerson
Nately Jamerson

Reputation: 313

perform browser action with node.js with using API

I want to do some event eg. clicks in a website. I can do it in chrome with javascript (or chrome extension), but is it possible to do without opening chrome but with server side code? No API is provided. It's not scraping but perform some sort of action.

Upvotes: 1

Views: 534

Answers (1)

bman
bman

Reputation: 5233

NodeJS uses Google V8 engine to interpret the JavaScript code. It does not run in a browser environment and therefore it lacks DOM and event handling. However, you can actually mock browser in NodeJS environment using mock-browser package.

const MockBrowser = require('mock-browser/lib/MockBrowser')

const mockBrowser = new MockBrowser()

global.window = mockBrowser.getWindow()
global.document = mockBrowser.getDocument()
global.navigator = mockBrowser.getNavigator()

However, you should be careful with this approach, as some methods (e.g. getComputedStyle) still will not work.

Maybe you should reconsider why you want to use DOM and events on the server side.

PhantomJS: Headless browser for NodeJS

PhantomJS is a headless browser for NodeJS that is used for testing, scraping, etc. It provides you with a full-featured browser that can simulate a browser.

Using CasperJS for scraping

If you want to scrape websites, you may use a library called CasperJS that itself uses PhantomJS. An example:

var casper = require('casper').create();
var links;

function getLinks() {
// Scrape the links from top-right nav of the website
    var links = document.querySelectorAll('ul.navigation li a');
    return Array.prototype.map.call(links, function (e) {
        return e.getAttribute('href')
    });
}

// Opens casperjs homepage
casper.start('http://casperjs.org/');

casper.then(function () {
    links = this.evaluate(getLinks);
});

casper.run(function () {
    for(var i in links) {
        console.log(links[i]);
    }
    casper.done();
});

Upvotes: 1

Related Questions