Skip to content

Quick Start: Connect

This chapter uses a simple script to demonstrate how to start a specified Mbbrowser environment and take control of it through code.

Practical Script

Please create a file named start.js and copy the following code into it:

javascript
const puppeteer = require('puppeteer-core');
const axios = require('axios'); // Ensure you run: npm install axios

async function startProject() {
  // 1. Setup configuration info
  const API_URL = 'http://127.0.0.1:8186'; // ApiServer Address
  const SESSION_ID = '373808cb37bd63f5f7d92415e736e85f'; // Your Environment ID

  try {
    // 2. Call Mbbrowser interface to start the environment
    console.log('Starting Mbbrowser environment...');
    const response = await axios.post(`${API_URL}/api/v1/browser/start`, {
      Session_ID: SESSION_ID
    });

    if (response.data.code === 0) {
      // 3. Get WebSocket connection address
      const wsEndpoint = response.data.data.ws;
      console.log('Environment started successfully, taking control...');

      // 4. Use Puppeteer to connect to this environment
      const browser = await puppeteer.connect({
        browserWSEndpoint: wsEndpoint,
        defaultViewport: null // Use browser's default window size
      });

      // 5. Open a new page and navigate
      const page = await browser.newPage();
      await page.goto('https://www.mbbrowser.com', { waitUntil: 'networkidle2' });

      console.log('Current Page Title:', await page.title());

      // 6. Disconnect after operation (The environment remains running unless you call the stop interface)
      await browser.disconnect();
      console.log('Automation operation complete!');
      
    } else {
      console.error('Environment startup failed:', response.data.message);
    }
  } catch (error) {
    console.error('Connection error:', error.message);
  }
}

startProject();

Key Concept Insights

  1. axios.post: First, send a request to ApiServer to open the environment. Without the environment running, Puppeteer has nothing to connect to.
  2. wsEndpoint: This is the "unique key" returned upon success. Puppeteer uses this address to enter the browser's interior.
  3. puppeteer.connect: Note that it is connect (connecting to an existing browser) rather than launch (starting a new browser). This is the core difference in fingerprint browser automation.
  4. browser.disconnect: It's recommended to disconnect when your script is finished. This way, even if the script ends, the browser window typically remains on the desktop, allowing for observation or follow-up manual operations.

TIP

Mastered taking over environments? The next chapter Core API Reference will teach you how to make the browser execute more complex commands.