I need to intercept .jpg
and .gif
images and replace them with a base64 image instead. The base64 images would then be visible in the screenshot.
The below code prevents the original image from loading, but the base64 image is not loaded in the place of the original images.
How can I replace the original image's src with the base64 image?
await page.setRequestInterception(true);
page.on('request', request => {
const resourceUrl = request.url().toLowerCase();
const base64Image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAADwBAMAAACDA6BYAAAAMFBMVEUAAACHh4fExMQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACKW9M+AAAACXBIWXMAAAsTAAALEwEAmpwYAAADM0lEQVR4AezOgQAAAAjAsFK5P2QgbQQbAAAAAAAAAAAAAN7bSlBQUFDw2LXDnLdBGADDgRMYnwB8/0Nurb1XUKVaNg2CtPjHlzjxlEekAaedh5rJz00xK3GkmFmTSJKyH9VlHfD1V81ewuybMLwiSs2iSjjXVgLTG9ASKKc6g6wFMM7VhcAYrtiIH0RL5sDEqXXAMWqHYMhIyawuBDa/bHsfa46QI4VC31kJoJq1+LsIyKa7PLLqpxrOw7jRq4CB8Sw7pqgATN2dFmRxcCmwAYzIAKPehAJdCZRzYLIBeHwC60IgF0wAiz+qbgYILN8JhDcC1YHEnUC1C8B2HzDZ3sBYLUreFqisaucPCXEPkGMA+2lmB2AKkn6ZqHcDni91Re4E0hB8Ngv9ObkLGKSkQ7ul5pVGdudDQtTvDWu7Eag2KAZg6ux3ryQlgNlBSiXvJPeuxfXo35oaLSCDeRvQ0xLn4sW961EL7/R7xd8O2wO0Int/2cRKsi2QaHsCFWDdE5gAHpuGstDtGklts7n5iSeeeOKJJ554Yvfes1z82f3CF4KJin8JtLY70OruQNseKLsD66ZAdtquQF4ltwbmT2DSmBzJmpwBk5/gN9syCZgAGnlciMw6YO6eKt+Lg1aXANP47YtaeAFaKAw6/6jMusWNA4jM4mSEeKHXVep8n2TWQ1LHgTy7cg0gXw5SRzIJWMaJOsd/6wkuWXMgA5jGn8OwT1/qlBvudxV1AH3XE4Y/45zfLEQa29xxPenufcWpAdNJQA7A9GvBOKyIYzjPB4OyicB2AszDlTkEof/kMqx5frPAJbiydMCT7pGyqUC7DmS8CcpmdTPKI3gNaJ9AmQpkabgOlKVAnr3rwLo1sF+5CR6SycDv04wWcWD9VdABKVsKVICsK5k5j0H7AOocoAE8X+qC0y9rmHIrHWxau2X1W7PABmA26thMaxYI+dpu0UcxnJhpviibB/x9w9oAxs2lTrpkFvAPWn42Q12eDJTrL00UjnVRNbvd+v7aKd0sR9rVJd+fAOTl+/KLO7PeUJfe+wD/5/jRHhwTAAAAAAzp33oldmIGAAAAAAAAAAAAAAAAATWgPUYJ011oAAAAAElFTkSuQmCC';
if (request.resourceType() == 'image' && resourceUrl.indexOf('.png') === -1 &&
resourceUrl.indexOf('.svg') === -1 ||
resourceUrl.indexOf('.jpg') !== -1 ||
resourceUrl.indexOf('.jpeg') !== -1 ||
resourceUrl.indexOf('.gif') !== -1) {
request.respond({
status: 200,
contentType: 'image/jpeg',
headers: {
// location: base64Image
// path: base64Image
url: base64Image
},
});
return; // prevent calling continue twice
}
request.continue();
});
request.respond
cannot be used with base64
reponses. Quote from the docs :
NOTE Mocking responses for dataURL requests is not supported.
Instead, you can answer with the buffered data which you need to convert from base64
to its binary representation first:
const base64Data = 'iVBORw0KGgoAAA...'; // ony the base64 data, without "data:image/png;base64,"
const buffer = Buffer.from(base64Data, 'base64');
// ...
request.respond({
status: 200,
contentType: 'image/png',
body: buffer
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.