Automated Facebook Login with Puppeteer

Automated Facebook Login with Puppeteer

Take the first step towards automating repetitive tasks in Facebook

Cover Photo by Alex Haney on Unsplash

Introduction

We get involved in a lot of boring and time-consuming tasks quite often. These tasks might be simple, yet they consume a lot of time. I initially started exploring puppeteer to find a way to schedule my posts on Facebook. And I did reach that goal. You, too, could build really cool apps with puppeteer and Facebook. For example, you can build an app to wish your friends on their birthdays. You can even build an app to post content automatically without your intervention on several pages. This can be very helpful if you want to post the same content to many groups and pages.

NOTE: Kindly note that you should always use Facebook responsibly. You should not use this tool to spam as it may lead your profile to be blocked from Facebook.

Let’s Start Building

Installing the necessary packages

npm i puppeteer

This will install puppeteer into your project.

Although this is an automated sign-in process, it needs your username and password to function. You should save your username and password in a file named config.json.

image.png

Once you complete that step, make sure you create an empty file named cookies.json. This file will be used to save the cookies from Facebook, which will be used to identify yourself as a user.

Writing the entry point async code

The await keyword can only be used inside of a function marked with the async keyword. Since the code we're executing is not currently in a function, we'll have to put it inside of one. One way to do this is with an "async IIFE" (immediately invoked function expression).

We will write this code in our index.js file.

const puppeteer = require('puppeteer');
const fs = require('fs');

const config = require('./config.json');
const cookies = require('./cookies.json');

(async () => {
    console.log('Hello World');
    //insert code here
})();

As you can see, we are importing the config.json and cookies.json files, as shown above.

Creating the browser instance

let browser = await puppeteer.launch({
    headless: false
});

const context = browser.defaultBrowserContext();

context.overridePermissions("https://www.facebook.com", []);

In the code snippet above, we are creating a headless browser. We are also overriding any permissions for ‘facebook.com’. The reason for this is that when you log in to Facebook, you will be annoyed with a popup asking whether to allow notifications. This can lead to problems when you are automating a task. Hence we call the overrridePermissions function to avoid that.

Creating the page instance

let page = await browser.newPage();

await page.setDefaultNavigationTimeout(100000);

await page.setViewport({
    width: 1200,
    height: 800
});

In the above code, we are creating an instance of a page and setting the default navigation timeout to 100000 milliseconds. We also set the viewport of the page to be 1200px width and 800px height. You can change these values as necessary.

Login to Facebook

Since this is an automated process, we should have a way to identify whether the user is already logged in. We do that by analyzing the cookies.json file. If the cookies.json file contains any values, we consider the user to be logged in as the file would be empty when we initially create the project.

if (!Object.keys(cookies).length) {

    await page.goto("https://www.facebook.com/login", {
        waitUntil: "networkidle2"
    });

    await page.type("#email", config.username, {
        delay: 30
    })

    await page.type("#pass", config.password, {
        delay: 30
    })

    await page.click("#loginbutton");

    await page.waitForNavigation({
        waitUntil: "networkidle0"
    });

    await page.waitFor(15000);

    try {

        await page.waitFor('[data-click="profile_icon"]');

    } catch (err) {

        console.log("failed to login");

        process.exit(0);

    }

    let currentCookies = await page.cookies();

    fs.writeFileSync('./cookies.json', JSON.stringify(currentCookies));

} else {

    //User Already Logged In

}

In the above code, we go to the page ‘https://www.facebook.com/login’ and wait until the network requests become idle, which implies the page has fully loaded. Next, we select the element with id email and type the username taken from the config file. And then, we select the element with id pass and type the password taken from the config file. Once that is done, we select the element with id loginbutton and click it.

We wait for a while until the network idles and another 15000 milliseconds just to be sure, and we perform a check to see whether the login was successful.

We check whether the [data-click=”profile_icon”] is present. If not, it will throw an error. Hence we wrap that statement in a try-catch block. If there is an error, we terminate the process.

On successful initial login, we get the cookies of the page and save it to a variable named currentCookies. Then we stringify the currentCookies JSON and save it to the cookies.json file using the fs.writeFileSync function. The cookies saved in this process will be used by Facebook when identifying the user and session.

Already logged into Facebook

We wrote the code to login to Facebook for the first time. Now we have to write a code to login to Facebook without providing any credentials. We will be using the cookies file we stored in the previous step.

else {

    //User Already Logged In

    await page.setCookie(...cookies);

    await page.goto("https://www.facebook.com/", {
        waitUntil: "networkidle2"
    });

}

We write the above code in the else block. We set the page cookies as the cookies we retrieved from cookies.json file. Facebook can now identify us and our session. Hence we won’t be required to enter our credentials once again when we login to Facebook.

End Result

Congratulations!! You have built an automated flow to login into Facebook. Now you have successfully completed the first step into automating your applications. Now you can automate repetitive, boring tasks on Facebook like wishing friends on their birthdays, replying to birthday wishes on your wall, etc.

NOTE: Kindly note that you should always use Facebook responsibly. You should not use this tool to spam as it may lead your profile to be blocked from Facebook.