Skip to content

Commit

Permalink
fix: clean up tmp profile dirs when browser is closed (#8580)
Browse files Browse the repository at this point in the history
* fix: clean up tmp profile dirs when browser is closed
  • Loading branch information
pablomatiasgomez committed Jun 27, 2022
1 parent f2e9cbb commit 9787a1d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
5 changes: 2 additions & 3 deletions src/node/ChromeLauncher.ts
Expand Up @@ -92,14 +92,15 @@ export class ChromeLauncher implements ProductLauncher {
}
}

let isTempUserDataDir = true;
let isTempUserDataDir = false;

// Check for the user data dir argument, which will always be set even
// with a custom directory specified via the userDataDir option.
let userDataDirIndex = chromeArguments.findIndex(arg => {
return arg.startsWith('--user-data-dir');
});
if (userDataDirIndex < 0) {
isTempUserDataDir = true;
chromeArguments.push(
`--user-data-dir=${await fs.promises.mkdtemp(
path.join(tmpdir(), 'puppeteer_dev_chrome_profile-')
Expand All @@ -111,8 +112,6 @@ export class ChromeLauncher implements ProductLauncher {
const userDataDir = chromeArguments[userDataDirIndex]!.split('=', 2)[1];
assert(typeof userDataDir === 'string', '`--user-data-dir` is malformed');

isTempUserDataDir = false;

let chromeExecutable = executablePath;
if (channel) {
// executablePath is detected by channel, so it should not be specified by user.
Expand Down
29 changes: 29 additions & 0 deletions test/src/launcher.spec.ts
Expand Up @@ -251,6 +251,35 @@ describe('Launcher specs', function () {
// This might throw. See https://github.com/puppeteer/puppeteer/issues/2778
await rmAsync(userDataDir).catch(() => {});
});
itChromeOnly('tmp profile should be cleaned up', async () => {
const {defaultBrowserOptions, puppeteer} = getTestState();

// Set a custom test tmp dir so that we can validate that
// the profile dir is created and then cleaned up.
const testTmpDir = await fs.promises.mkdtemp(
path.join(os.tmpdir(), 'puppeteer_test_chrome_profile-')
);
process.env['PUPPETEER_TMP_DIR'] = testTmpDir;

// Path should be empty before starting the browser.
expect(fs.readdirSync(testTmpDir).length).toEqual(0);
const browser = await puppeteer.launch(defaultBrowserOptions);

// One profile folder should have been created at this moment.
const profiles = fs.readdirSync(testTmpDir);
expect(profiles.length).toEqual(1);
expect(profiles[0]?.startsWith('puppeteer_dev_chrome_profile-')).toBe(
true
);

// Open a page to make sure its functional.
await browser.newPage();
await browser.close();
// Profile should be deleted after closing the browser
expect(fs.readdirSync(testTmpDir).length).toEqual(0);
// Restore env var
process.env['PUPPETEER_TMP_DIR'] = '';
});
itFirefoxOnly('userDataDir option restores preferences', async () => {
const {defaultBrowserOptions, puppeteer} = getTestState();

Expand Down

0 comments on commit 9787a1d

Please sign in to comment.