File size: 1,542 Bytes
6c6d16c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { Browser, chromium } from 'playwright';

class BrowserManager {
    private static instance: Browser | null = null;
    private static isInitializing = false;
    private static initPromise: Promise<Browser> | null = null;

    static async getInstance(): Promise<Browser> {
        if (this.instance && this.instance.isConnected()) {
            return this.instance;
        }

        if (this.isInitializing) {
            return this.initPromise!;
        }

        this.isInitializing = true;
        this.initPromise = this.initializeBrowser();
        
        try {
            this.instance = await this.initPromise;
            return this.instance;
        } finally {
            this.isInitializing = false;
            this.initPromise = null;
        }
    }

    private static async initializeBrowser(): Promise<Browser> {
        return chromium.launch({
            headless: process.env.NODE_ENV === 'development' ? false : true,
            args: [
                '--no-sandbox',
                '--disable-setuid-sandbox',
                '--disable-dev-shm-usage',
                '--disable-blink-features=AutomationControlled',
                '--disable-infobars',
                '--window-size=1920,1080'
            ],
            executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
        });
    }

    static async closeBrowser() {
        if (this.instance) {
            await this.instance.close();
            this.instance = null;
        }
    }
}

export default BrowserManager;