Upload a local image file via puppeteer connect on Chrome extension - file-upload

Task: I'm building a chrome extension with a popup (panel_chatwindow.js) window (standalone window). I want to take a local image file (e.g., /1.png) and upload it to a website that has a <input type='file'/> element (e.g., any services that require to upload a user photo).
Note
Other than upload file, the code can execute other web macro just fine.
My current code:
let browserWSEndpoint = "";
const puppeteer = require("puppeteer");
async function initiatePuppeteer() {
await fetch("http://localhost:9222/json/version")
.then((response) => response.json())
.then(function (data) {
browserWSEndpoint = data.webSocketDebuggerUrl;
})
.catch((error) => console.log(error));
}
initiatePuppeteer();
$("#puppeteer-button").on("action", doPuppeteerThings);
// Assign button to puppeteer function
async function doPuppeteerThings(event, actionArray) {
const browser = await puppeteer.connect({
browserWSEndpoint: browserWSEndpoint,
});
const page = await browser.newPage();
await page.setViewport({
width: 1600,
height: 1000,
});
await page.goto("website", {
waitUntil: "networkidle2",
});
await page.waitForSelector("input[type=file]");
await page.waitFor(2000);
const input = await page.$('input[type="file"]');
await input.uploadFile("/1.PNG");
})
Error message on popup window console (panel_chatwindow.js)
panel_chatwindow.js:160 is the await input.uploadFile("/1.PNG"); line
Using puppeteer.launch works perfectly fine with the code, i.e., can upload a local file to a website once launching the node server.
I don't have to use puppeteer to upload image files, any other way on chrome extension would be just fine.
I'm aware of this post: https://github.com/puppeteer/puppeteer/issues/4405 but i am not able to address my issue with any answers in the thread.

Related

API call working in chrome but not postman

I am trying to call this API endpoint https://core-api.prod.blur.io/v1/collections/doodles-official/tokens?filters=%7B%22traits%22%3A%5B%5D%2C%22hasAsks%22%3Atrue%7D in a backed environment.
It work in google chrome, but when I try to make a request through node.js or postman, I get a status 403 'Forbidden'.
I added all the Chrome request headers in my options object but it still doesn't work.
const getListings = async function() {
const options = {
/* Add whatever Chrome display in the Network settings tab of the request */
};
const res = await fetch(`https://core-api.prod.blur.io/v1/collections/mutant-ape-yacht-club/tokens?filters=%7B%22traits%22%3A%5B%5D%2C%22hasAsks%22%3Atrue%7D`, options)
.then(res => {
console.log(res);
return res.json();
})
.catch(err => console.log(err));
return res;
}
I simply would like to use this URL that works in the browser in my backend application. I don't understand how this can work in my browser and not in a backed environment.

TypeScript Playwright: Saving Storagestate via Sign in via API request and then using inside BowserContext does not work - takes me back to login page

I need to decide whether to go with Playwright as an E2E Automation tool or not.
The following piece of code using backend API for sign in is working fine.
But when I use the saved Storagestate file inside the BrowserContext, then it fails to sign me in, hence taking me back to the Login page.
test.describe('User login', async () => {
var browser: any;
test.beforeEach(async () => {
browser = await chromium.launch({
channel: 'chrome',
headless: false
});
});
const requestContext = await request.newContext();
const response = await requestContext.post(`${testConfig.envConfig.apiURL}/login/authorize`, {
form: {
'email': 'user.tech+admin#xxxx.com',
'password': 'xxxxxx'
}
});
const responseJson = await response.json();
console.log(responseJson);
expect(response.ok()).toBeTruthy();
// Save signed-in state.
await requestContext.storageState({ path: './.storagestates/adminUserStorageState.json' });
await requestContext.dispose();
// Using the Storagesate in the BrowserContext
// page should sign in as a admin user.
test.use({ storageState: './.storagestates/adminUserStorageState.json' });
test('Version 1: Cookies stored via Auth. by backend API', async ({ page }) => {
let url = `/brand/f99f06fb1f121234aaf/gallery`;
await page.goto(url, {timeout: 60000});
});
test('Version 2: Cookies stored via Auth. by backend API', async () => {
// page should sign in as a buyer user.
const userContext = await browser.newContext({ storageState: './.storagestates/buyerUserStorageState.json' });
const page = await userContext.newPage();
await page.goto(`/`, {timeout: 60000});
});
});

logging in with cypress/puppeteer

I have an application that uses Okta to log in. I am trying to set up an automation test using Cypress with Puppeteer. The problem I am having is that when I launch puppeteer with {headless: true}, it doesn't fill in the login form. {headless: false} opens another browser window outside of Cypress and works as expected. It fills in the login form, logs in correctly, but I can't run any cypress tests in that window.
on('task', {
login({username, password}) {
return (async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto(config.baseUrl);
await page.waitForNavigation();
await page.waitFor('#okta-signin-username');
await page.type('#okta-signin-username', username, {delay: 100});
await page.waitFor('#okta-signin-password');
await page.type('#okta-signin-password', password, {delay: 100});
await page.click('#okta-signin-submit');
await page.waitForNavigation();
return true;
};
});
Here's how it's being used:
it('my test', () => {
cy.visit('/');
cy.viewport(1280, 1024);
cy.login('username', 'password');
//tests go here
});
The above code opens Chromium and correctly logs in but then the tests fail. It doesn't log in with {headless: true}. Am I missing something here?
Any help would be appreciated.
Thanks

page.goto (puppeteer) does not stop calling itself when opening the same url it is navigating to

I am trying to convert an html web page into a pdf file by using puppeteer. It is converting the html web page into pdf file but the problem is that, page.goto is not stopping after its job is done. When this happens, the terminal I run this localhost server from becomes a little unresponsive. I also deployed it on heroku but when I visit the url, the server responds me with error code 503 and it does not convert to pdf there.
let printPDF = async () => {
try {
const browser = await puppeteer.launch({ headless: true});
const page = await browser.newPage();
await page.goto('http://localhost:3000/preview')
await page.pdf({ format: 'A4' , path: `${__dirname}/contact.pdf`, printBackground: true});
await page.close();
await browser.close();
console.log("repeat") //logging to see its repetition
}
catch (error) {
await page.close();
await browser.close();
}
}
getReviewPage = ((req, res) => {
printPDF()
res.sendFile(`${__dirname}/form.html`)
})
app.route('/preview').get(getReviewPage);
Since printPDF is an async function returning Promise, you need to wait for it to finish, with then for example:
const getReviewPage = (req, res) => {
printPDF().then(() => res.sendFile(`${__dirname}/form.html`)
}

puppeteer hangs chromium on request.continue if header is modified on 302 response code

Chromium is getting hanged if header is modified using puppeteer
Puppeteer version:1.12.2
Platform / OS version: MAC / UBUNTU
'use strict';
const puppeteer = require('puppeteer');
(async () => {
try {
let browser = await puppeteer.launch({ headless: false });
let [page] = await browser.pages();
await page.setRequestInterception(true);
page.on('request', request => {
const headers = Object.assign({}, request.headers(), {
foo: 'bar'
});
request.continue({ headers });
});
await page.goto('http://google.com');
} catch (err) {
console.error(err);
}
})();
In my case, this was not relevant to setting headers.
When I enabled request interception with this line of code observing the same behavior:
await page.setRequestInterception(true);
If I comment out this line of code it is loading the page but the Chromium is complaining that the connection is insecure. In this case waitUntil option does not work within page.goto as option.
If I open a new tab in Chromium (the same window) and copy and paste the same url it is loading the page without any isues.