|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2024 Google Inc. |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | +import { |
| 7 | + connect, |
| 8 | + ExtensionTransport |
| 9 | +} from "puppeteer-core/lib/esm/puppeteer/puppeteer-core-browser.js"; |
| 10 | + |
| 11 | +globalThis.testConnect = async (url) => { |
| 12 | + // Get the current active tab instead of creating a new one |
| 13 | + const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); |
| 14 | + |
| 15 | + const browser = await connect({ |
| 16 | + transport: await ExtensionTransport.connectTab(tab.id) |
| 17 | + }); |
| 18 | + |
| 19 | + const [page] = await browser.pages(); |
| 20 | + const title = await page.title(); |
| 21 | + |
| 22 | + await browser.disconnect(); |
| 23 | + return title; |
| 24 | +}; |
| 25 | + |
| 26 | +globalThis.highlightLinks = async () => { |
| 27 | + const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); |
| 28 | + |
| 29 | + const browser = await connect({ |
| 30 | + transport: await ExtensionTransport.connectTab(tab.id) |
| 31 | + }); |
| 32 | + |
| 33 | + const [page] = await browser.pages(); |
| 34 | + |
| 35 | + await page.evaluate(() => { |
| 36 | + const links = document.querySelectorAll("a"); |
| 37 | + links.forEach((link) => { |
| 38 | + link.style.backgroundColor = "yellow"; |
| 39 | + link.style.border = "2px solid red"; |
| 40 | + }); |
| 41 | + return `Highlighted ${links.length} links`; |
| 42 | + }); |
| 43 | + |
| 44 | + await browser.disconnect(); |
| 45 | + return `Highlighted all links on the page`; |
| 46 | +}; |
| 47 | + |
| 48 | +// Add message listener |
| 49 | +chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { |
| 50 | + if (request.action === "testConnection") { |
| 51 | + globalThis |
| 52 | + .testConnect(request.url) |
| 53 | + .then((title) => sendResponse(`Current page title: ${title}`)) |
| 54 | + .catch((error) => sendResponse(`Error: ${error.message}`)); |
| 55 | + return true; // Will respond asynchronously |
| 56 | + } else if (request.action === "highlightLinks") { |
| 57 | + globalThis |
| 58 | + .highlightLinks() |
| 59 | + .then(sendResponse) |
| 60 | + .catch((error) => sendResponse(`Error: ${error.message}`)); |
| 61 | + return true; |
| 62 | + } |
| 63 | +}); |
0 commit comments