Puppeteer - How to pass back and forth a date (or a complex type) to the headless browser via the evaluate function

1 - About

A step by step guide that shows how to serialize and deserialize an object with a date (

It will also work for other complex type

) when using the puppeteer evaluate function.

3 - Steps

3.1 - The object

This is the example object that has a date property that we will pass to the browser.


let dayObj = {
	"name": "saturday",
	"date": new Date(2020, 1, 25)
}

3.2 - The serialization

From and to the evaluate function, you need to pass a serialized object (ie object that are stringified).


let dayJson = JSON.stringify(dayObj);


console.log(dayJson);


{"name":"saturday","date":"2020-02-24T23:00:00.000Z"}"

3.3 - The script execution via the evaluate function

We have string, we can pass it to the evaluate function and return any other object back by serializing it (ie stringified)


let dayJsonFromBrowser = await page.evaluate((dayJsonInBrowser) => {
	// To make it an object back, you can parse it
	let dayObjInBrowser = JSON.parse(dayJsonInBrowser);
	// And pass it back again with stringify
	return JSON.stringify(dayObjInBrowser);
}, dayJson);

3.4 - The deserialization

3.4.1 - JSON.parse and the reviver function

After receiving a serialized object back from the evaluate function, you need to rebuild it with the JSON.parse function and a reviver function. The reviver get as arguments, the key and the value of each property of the object and this is where you can build the object back as a date.


let dayObjFromBrowser = JSON.parse(dayJsonFromBrowser, (key, value) => {
	// The key of the properties
	if (key == 'date') {
		// if the name of the properties is date, deserialize it (ie make it a date)
		return new Date(value);
	} else {
		return value;
	}
})

  • Are they the same ? (Jest assertion)

expect(dayObj).toEqual(dayObjFromBrowser);


PASS

3.4.2 - The object type

If you have an object with a function, you can cast the object to its original type with the Object.assign function.

Example:

  • We can create a class that will add a getDate function (typescript)

class day {
	name: string;
	date: Date;

	constructor(name: string, date: Date){
		this.name = name;
		this.date = date;
	}

	getDate(){
		return this.date;
	}
}

  • To cast the object that we got from the previous JSON.parse step, we can create a dummy object and assign it.

const dummObject = new day("", new Date());
let dayType = Object.assign(dummObject, dayObjFromBrowser);

  • Does the new object, has the new getDate function and does it return the good date ?

// jest assertion
expect(dayType.getDate()).toEqual(new Date(2020, 1, 25));


PASS

4 - Documentation / Reference


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap