ulixee / hero

The web browser built for scraping
MIT License
652 stars 32 forks source link

[QUESTION] Resize the view port on a specific tab #150

Closed Baker68 closed 1 year ago

Baker68 commented 1 year ago

Is there any way to resize the view port on a specific tab ?

Or maybe interact with the devtools to send Emulation.clearDeviceMetricsOverride and Emulation.setDeviceMetricsOverride commands ? Thanks in advance

blakebyrnes commented 1 year ago

Each Hero instance can set a viewport in the constructor. How are you opening "tabs"?

Baker68 commented 1 year ago

Each Hero instance can set a viewport in the constructor. How are you opening "tabs"?

I`m clicking on a link that opens in a new tab.

await _hero.click(el);
const tab = await _hero.waitForNewTab();
blakebyrnes commented 1 year ago

Ah, gotcha. Can you tell me a bit more about your use case? Are you wanting the whole "window" to resize? Or just the virtual area of the one tab?

You can do what you're talking about pretty easily with a plugin.

Baker68 commented 1 year ago

Not the whole window, just the virtual area of the new tab.

blakebyrnes commented 1 year ago
const pluginId = '@baker68/resizer'
export default class ResizeClientPlugin extends ClientPlugin {
  public static override id = pluginId;
  public static coreDependencyIds = [pluginId];

  public onTab(hero: Hero, tab: Tab, sendToCore: ISendToCoreFn): void {
    tab.resize = function(contentSize) {
      return sendToCore(pluginId, contentSize);
    }
  }
}

export default class ResizeCorePlugin extends CorePlugin {
  public static override id = pluginId;

  public async onClientCommand(
    { frame, page }: IOnClientCommandMeta,
    contentSize,
  ): Promise<any> {
    await page.devtoolsSession.send('Emulation.setDeviceMetricsOverride', {
          ...contentSize,
          mobile: false,
     });
  }
}
blakebyrnes commented 1 year ago

You'll want something like this (didn't test it..)

Baker68 commented 1 year ago

yes @blakebyrnes ; I've just realized that it's exposed in the CorePlugin , for some reason I was looking for it in the ClientPlugin. Thank you @blakebyrnes !

Baker68 commented 1 year ago

You'll want something like this (didn't test it..)

const pluginId = '@baker68/resizer'
export default class ResizeClientPlugin extends ClientPlugin {
  public static override id = pluginId;
  public static coreDependencyIds = [pluginId];

  public onTab(hero: Hero, tab: Tab, sendToCore: ISendToCoreFn): void {
    tab.resize = function(contentSize) {
      return sendToCore(pluginId, contentSize);
    }
  }
}

export default class ResizeCorePlugin extends CorePlugin {
  public static override id = pluginId;

  public async onClientCommand(
    { frame, page }: IOnClientCommandMeta,
    contentSize,
  ): Promise<any> {
    await page.devtoolsSession.send('Emulation.setDeviceMetricsOverride', {
          ...contentSize,
          mobile: false,
     });
  }
}

For the record : It works.