123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- // background.js
- chrome.runtime.onInstalled.addListener(function () {
- console.log("插件已被安装");
- });
- let pageState = 0; // 0 - 未创建,1 - 已创建
- let pageInfo = null;
- let pageId = "";
- let tabId = "";
- chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
- if (request.action === "show_popup") {
- tabId = sender.tab.id;
- pageInfo = request;
- pageInfo.tabId = tabId;
- try {
- await chrome.tabs.get(pageId);
- } catch {
- pageState = 0; // 说明没找到
- }
- if (pageState === 0) {
- chrome.windows.create(
- {
- url: chrome.runtime.getURL("page.html"), // 指向你的弹出页面
- type: "popup", // 设置为弹出窗口
- width: 1000,
- height: 750,
- focused: true,
- left: 100, // 可选,窗口的左边缘
- top: 100, // 可选,窗口的上边缘
- },
- (newTab) => {
- pageId = newTab.tabs[0].id;
- pageState = 1;
- }
- );
- } else {
- chrome.tabs.get(pageId, (tab) => {
- if (tab) {
- chrome.windows.update(tab.windowId, { focused: true });
- chrome.tabs.update(pageId, { active: true });
- sendTabMessage(pageId, pageInfo);
- }
- });
- }
- }
- });
- // 监听已更新的标签,以找出何时打开了 page.html
- chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
- if (changeInfo.status === "complete" && tab.url.includes("page.html")) {
- sendTabMessage(tabId, pageInfo);
- }
- });
- function sendTabMessage(tabId, data) {
- chrome.tabs.sendMessage(tabId, {
- msgToPopup: "发送页面",
- data,
- pageState: pageState,
- });
- }
- // // background.js
- // chrome.runtime.onInstalled.addListener(function () {
- // console.log("插件已被安装");
- // });
- // let jsRequests = [];
- // let jsRequestsByTab = {}; // 用于存储每个标签页的请求
- // chrome.webRequest.onBeforeRequest.addListener(
- // (details) => {
- // const tabId = details.tabId; // 获取当前请求的标签页 ID
- // const url = details.url;
- // let uri = new URL(url);
- // if (
- // details.initiator &&
- // uri.pathname.endsWith(".js") &&
- // (uri.protocol.startsWith("http") || uri.protocol.startsWith("https"))
- // ) {
- // // 确保有个数组来记录当前标签页的请求
- // if (!jsRequestsByTab[tabId]) {
- // jsRequestsByTab[tabId] = [];
- // }
- // jsRequestsByTab[tabId].push(url);
- // }
- // },
- // { urls: ["<all_urls>"] }
- // );
- // chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
- // if (request.action === "getJsRequests") {
- // const tabId = sender.tab.id; // 获取请求来源的标签页 ID
- // sendResponse(jsRequestsByTab[tabId] || []);
- // }
- // });
- // // 监听标签页更新(包括刷新)事件以清空请求记录
- // chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
- // if (changeInfo.status === "loading") {
- // // 标签页加载完成时清空请求记录
- // delete jsRequestsByTab[tabId];
- // }
- // });
- // // 监听标签页关闭事件以清空请求记录
- // chrome.tabs.onRemoved.addListener((tabId) => {
- // delete jsRequestsByTab[tabId]; // 清空对应标签页的请求记录
- // });
|