Skip to content

Quick Start: Taking Control of Mbbrowser Environment

This chapter provides complete, runnable scripts for three languages. Choose the one you're most familiar with and follow along. The core logic remains identical: request the ws address from ApiServer, then use connectOverCDP to take control of Mbbrowser.


Method 1: JavaScript / Node.js Version

Create a file named start.js:

javascript
const { chromium } = require('playwright');
const axios = require('axios');

// ============================
// Configuration (Fill in your actual info)
// ============================
const API_URL    = 'http://127.0.0.1:8186';
const SESSION_ID = 'replace_with_your_session_id';   // Right-click Mbbrowser environment → Copy Environment ID

async function main() {
  // ── Step 1: Tell ApiServer to open a specific environment ────────
  console.log('⏳ Opening Mbbrowser environment...');
  let wsEndpoint;
  try {
    const response = await axios.post(`${API_URL}/api/v1/browser/start`, {
      Session_ID: SESSION_ID
    });
    if (response.data.code !== 0) {
      console.error('❌ Environment startup failed:', response.data.message);
      return;
    }
    // ── Step 2: Extract WebSocket address (Playwright-specific field) ──
    wsEndpoint = response.data.data.ws;
    console.log('✅ Environment opened. ws address:', wsEndpoint);
  } catch (err) {
    console.error('❌ Could not connect to ApiServer. Ensure it is running!', err.message);
    return;
  }

  // ── Step 3: Use connectOverCDP to take control ─────────────────
  const browser = await chromium.connectOverCDP(wsEndpoint);
  console.log('🎉 Playwright takeover successful!');

  try {
    // ── Step 4: Get Current Context and Page ────────────────────
    // Mbbrowser environments have a default context; use the first one.
    const context = browser.contexts()[0];
    const page    = context.pages()[0] || await context.newPage();

    // ── Step 5: Execute Business Operations ─────────────────────
    await page.goto('https://www.mbbrowser.com', { waitUntil: 'domcontentloaded' });
    console.log('📄 Current Page Title:', await page.title());

    // Wait for 3 seconds for observation
    await page.waitForTimeout(3000);

    console.log('✅ Script execution finished!');
  } finally {
    // Disconnect Playwright (Mbbrowser window will continue running)
    await browser.close();
  }
}

main().catch(console.error);

Run:

bash
node start.js

Method 2: Python Version

Create a file named start_playwright.py:

python
import requests
from playwright.sync_api import sync_playwright

# ============================
# Configuration
# ============================
API_URL    = "http://127.0.0.1:8186"
SESSION_ID = "replace_with_your_session_id"


def get_ws_endpoint(session_id: str) -> str or None:
    """Calls Mbbrowser ApiServer to start environment and return ws address"""
    print("⏳ Opening Mbbrowser environment...")
    try:
        resp = requests.post(
            f"{API_URL}/api/v1/browser/start",
            json={"Session_ID": session_id},
            timeout=30
        )
        data = resp.json()
    except requests.exceptions.ConnectionError:
        print("❌ Could not connect to ApiServer! Ensure apiserver.exe is running.")
        return None

    if data.get("code") != 0:
        print(f"❌ Environment startup failed: {data.get('message')}")
        return None

    ws = data["data"]["ws"]
    print(f"✅ Environment opened. ws address: {ws}")
    return ws


def main():
    ws_endpoint = get_ws_endpoint(SESSION_ID)
    if not ws_endpoint:
        return

    with sync_playwright() as p:
        # ── connect_over_cdp to take control ─────────────────
        browser = p.chromium.connect_over_cdp(ws_endpoint)
        print("🎉 Playwright takeover successful!")

        # Take the existing default BrowserContext (preserves all Cookies, Storage, etc.)
        context = browser.contexts[0]
        # Take the first page; create one if none exist
        page = context.pages[0] if context.pages else context.new_page()

        # ── Execute Business Operations ──────────────────────────────
        page.goto("https://www.mbbrowser.com", wait_until="domcontentloaded")
        print(f"📄 Current Page Title: {page.title()}")

        page.wait_for_timeout(3000)
        print("✅ Script execution finished!")

        browser.close()


if __name__ == "__main__":
    main()

Run:

bash
python start_playwright.py

Method 3: Java Version

NOTE

For the Java version, we recommend using Mbbrowser Client's Automation Script Manager, which handles Playwright JAR bundles and driver extraction automatically. The following code is directly usable in the script editor.

java
import com.microsoft.playwright.*;
import java.net.URI;
import java.net.http.*;
import org.json.*;

public class MBPlaywright {
    static final String API_URL    = "http://127.0.0.1:8186";
    static final String SESSION_ID = "replace_with_your_session_id";

    public static void main(String[] args) throws Exception {
        // ── Step 1: Call ApiServer to Start Environment ──────────────
        System.out.println("⏳ Opening Mbbrowser environment...");
        HttpClient httpClient = HttpClient.newHttpClient();
        String body = "{\"Session_ID\":\"" + SESSION_ID + "\"}";
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(API_URL + "/api/v1/browser/start"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = httpClient.send(
            request, HttpResponse.BodyHandlers.ofString()
        );

        JSONObject data   = new JSONObject(response.body());
        String wsEndpoint = data.getJSONObject("data").getString("ws");
        System.out.println("✅ Environment opened. ws: " + wsEndpoint);

        // ── Step 2: Playwright connectOverCDP Takeover ───────────────
        // Set to skip built-in browser downloads
        System.setProperty("playwright.skip.browser.download", "1");

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().connectOverCDP(wsEndpoint);
            System.out.println("🎉 Playwright takeover successful!");

            BrowserContext context = browser.contexts().get(0);
            Page page = context.pages().isEmpty()
                ? context.newPage()
                : context.pages().get(0);

            page.navigate("https://www.mbbrowser.com");
            System.out.println("📄 Current Page Title: " + page.title());

            Thread.sleep(3000);
            System.out.println("✅ Script execution finished!");

            browser.close();
        }
    }
}

Line-by-Line Analysis

connectOverCDP vs launch: The Critical Difference

javascript
// ❌ Standard Playwright practice: Creates a new, blank Chrome window
const browser = await chromium.launch();

// ✅ Mbbrowser Playwright practice: Takes control of an existing fingerprint environment
const browser = await chromium.connectOverCDP(wsEndpoint);
ComparisonStandard launch()Mbbrowser connectOverCDP()
Browser StateBrand new, blankFull fingerprints, proxy, and Cookies exist
ConsequenceTarget site sees a bare Chrome botTarget site sees a "real user"
Multi-accountImpossible to differentiateAccurately matched via Session_ID

Why use data.ws instead of data.http?

FieldExample FormatSuitable Framework
data.http127.0.0.1:9222Selenium (debuggerAddress)
data.wsws://127.0.0.1:9222/devtools/browser/xxxPlaywright / Puppeteer

Playwright's connectOverCDP requires the full ws://... address.

browser.contexts()[0]: Do Not Create New Contexts

javascript
// ❌ WRONG: Creates a new context; Cookies and storage in Mbbrowser will be lost.
const context = await browser.newContext();

// ✅ CORRECT: Use Mbbrowser's existing context (preserves account state).
const context = browser.contexts()[0];

Troubleshooting

❓ Error: connect ECONNREFUSED 127.0.0.1:8186

ApiServer isn't started or the port is wrong. Ensure apiserver.exe is running in its terminal window.

❓ Error: Browser closed or Target page, context or browser has been closed

The Mbbrowser environment has been closed (timed out or manually). Call /api/v1/browser/start again.

browser.contexts() returns an empty array

When an environment is first opened, the default context might take a moment to initialize. Add a brief wait:

javascript
// Wait for context to appear (up to 5 seconds)
let context;
for (let i = 0; i < 50 && !browser.contexts().length; i++) {
  await new Promise(r => setTimeout(r, 100));
}
context = browser.contexts()[0];

❓ Does browser.close() close the Mbbrowser window?

In connectOverCDP mode, browser.close() only disconnects the Playwright link—it does not close the Mbbrowser window. To close it, call the stop interface:

javascript
await axios.post(`${API_URL}/api/v1/browser/stop`, { Session_ID: SESSION_ID });

TIP

Ready to code? The next chapter Core API Reference will teach you how to use Playwright's powerful Locator and Page APIs.