How to Open Browser with Pre Loaded Chrome Plugin in Playwright?

Sanjay Kumar
1 min readFeb 18, 2024

--

In many scenarios and use cases we need the pre-loaded chrome plugin in the browser window which is opened through Playwright.

It is simple to do that in Playwright. Just add the below code in your test script and make sure to replace the extension code path in the below code.

Please follow the tutorial mentioned at the bottom here for the live example.


import { test as base, chromium, type BrowserContext } from '@playwright/test';
import path from 'path';

export const test = base.extend<{
context: BrowserContext;
extensionId: string;
}>({
context: async ({ }, use) => {
const pathToExtension = path.join(__dirname, 'YourExtensionCodePath');
const context = await chromium.launchPersistentContext('', {
headless: false,
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`,
],
});
await use(context);
await context.close();
},
extensionId: async ({ context }, use) => {
/*
// for manifest v2:
let [background] = context.backgroundPages()
if (!background)
background = await context.waitForEvent('backgroundpage')
*/

// for manifest v3:
let [background] = context.serviceWorkers();
if (!background)
background = await context.waitForEvent('serviceworker');

const extensionId = background.url().split('/')[2];
await use(extensionId);
},
});
export const expect = test.expect;

--

--

Sanjay Kumar
Sanjay Kumar

Written by Sanjay Kumar

Founder and Creator of SelectorsHub, TestCase Studio, TestCaseHub & ChroPath | Speaker | Blogger | Automation Passionate