mbehzad
mbehzad

Reputation: 3878

How to proxy specific request in Puppeteer

is there a way to proxy / redirect specific urls to others? for example when Puppeteer page goes to "mydomain.com" i'd like all calls to "mydomain.com/styles/.css" be proxied to "localhost:8080/styles/.css". I don't want all request to be rediret through a proxy. but something similar to what https://chrome.google.com/webstore/detail/resource-override/pkoacgokdfckfpndoffpifphamojphii?hl=en chrome extension does.

Upvotes: 2

Views: 1491

Answers (2)

SilentTremor
SilentTremor

Reputation: 4912

For puppeteersharp, it took me a while to figure it out.

page = await ChromeDriver.NewPageAsync();
await page.SetRequestInterceptionAsync(true);
page.Request += new EventHandler<RequestEventArgs>(async delegate (object o, RequestEventArgs a)
{
    if (a.Request.Url.StartsWith("mydomain.com"))
    {
        await a.Request.ContinueAsync(new Payload
        {
            Headers = a.Request.Headers,
            Method = a.Request.Method,
            PostData = a.Request.PostData != null ? a.Request.PostData.ToString() :  "",
            Url = a.Request.Url.Replace("mydomain.com", "http://localhost:8080")
        });
    }
    else
    {
        await a.Request.ContinueAsync();
    }
});

Upvotes: 1

mbehzad
mbehzad

Reputation: 3878

as @Hellonearthis linked, the soulution seems to be

const page = await browser.newPage();

await page.setRequestInterception(true);

page.on('request', (request) => {
  if (request.url().indexOf("mydomain.com") !== -1) {
    // simply replace with another url
    request.continue((request.url().replace("mydomain.com", "http://localhost:8080/styles"));
  }
  else {
    request.continue();
  }

});

Upvotes: 2

Related Questions