You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Playwright中获取当前上下文?以及TypeScript环境下使用Playwright在新标签页打开URL时如何获取当前上下文(附C#实现示例)

Hey there! Let's tackle your two Playwright TypeScript questions based on your C# code example.

Playwright TypeScript: 获取当前上下文 + 新标签页打开URL

1. 获取当前上下文

In TypeScript, there are two straightforward ways to get the current BrowserContext:

  • From an existing Page instance: Every Page object has a context() method that returns its associated BrowserContext. This is perfect if you already have access to a page in your code:

    // Assuming you have a Page instance (e.g., from context.newPage())
    const currentContext = page.context();
    
  • Directly reference the context when creating it: When you initialize a context from a Browser, just store the reference for later use. This is ideal if you need to manage the context across multiple functions:

    import { chromium } from '@playwright/test';
    
    const browser = await chromium.launch();
    // Save this context reference to use anywhere in your code
    const currentContext = await browser.newContext();
    const page = await currentContext.newPage();
    

2. TypeScript实现新标签页打开URL(对应你的C#代码)

Here's the TypeScript equivalent of your C# method, using Playwright's native APIs. We'll use context.waitForPage() to handle the new tab creation, just like your RunAndWaitForPageAsync call:

import { Page } from '@playwright/test';

async function openUrlInNewTab(page: Page, url: string): Promise<number> {
  const context = page.context();
  
  // Wait for the new page to be created while triggering window.open
  const newPage = await context.waitForPage(async () => {
    await page.evaluate((targetUrl) => window.open(targetUrl), url);
  });

  // Wait for the new page to finish loading
  await newPage.waitForLoadState();

  // Return the index of the new page (same logic as your C# code)
  return context.pages().length - 1;
}

代码解释:

  • context.waitForPage() listens for a new page to be created in the context, and we trigger the creation by running window.open() via page.evaluate().
  • page.evaluate() is the TypeScript equivalent of your ExecuteJavaScript method—it runs the provided JS code in the browser context, passing the URL as an argument.
  • After the new page loads, we return the index of the last page in the context (since the new tab is the most recent one added).

内容的提问来源于stack exchange,提问作者Greg Finzer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:02:32