File size: 1,385 Bytes
fb38ec5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { Page } from "puppeteer-core";
import { NavigationEvent } from "../types/casting.js";
import { normalizeUrl } from "./url.js";

export const navigatePage = async (
  event: NavigationEvent["event"],
  targetPage: Page,
): Promise<void> => {
  if (event.action === "back") {
    await targetPage.goBack();
  } else if (event.action === "forward") {
    await targetPage.goForward();
  } else if (event.action === "refresh") {
    await targetPage.reload();
  } else if (event.url) {
    const formattedUrl = normalizeUrl(event.url) || event.url;
    await targetPage.goto(formattedUrl);
  }
};

export const getPageTitle = async (page: Page): Promise<string> => {
  try {
    return await page.title();
  } catch (error) {
    return "Untitled";
  }
};

export const getPageFavicon = async (page: Page): Promise<string | null> => {
  try {
    return await page.evaluate(() => {
      const iconLink = document.querySelector('link[rel="icon"], link[rel="shortcut icon"]');
      if (iconLink) {
        const href = iconLink.getAttribute("href");
        if (href?.startsWith("http")) return href;
        if (href?.startsWith("//")) return window.location.protocol + href;
        if (href?.startsWith("/")) return window.location.origin + href;
        return window.location.origin + "/" + href;
      }
      return null;
    });
  } catch (error) {
    return null;
  }
};