yjanb11

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

谷歌浏览器自动刷新插件

一个谷歌浏览器(版本 138.0.7204.50(正式版本) (64 位))的插件,实现可以按照单独的标签页自动刷新,并可以设置刷新时间,默认刷新时间是15分钟,标签页不在激活状态也可以自动刷新。

 

这个 Chrome 插件实现了按标签页设置自动刷新的功能,主要包含以下部分:

 

  1. 后台脚本 (background.js):
    • 使用 Map 存储每个标签的刷新配置
    • 每秒检查一次是否有标签需要刷新
    • 监听标签更新和关闭事件,管理刷新配置
  2. 弹出窗口 (popup.html 和 popup.js):
    • 简洁的界面,可设置刷新时间(秒 / 分钟)
    • 显示当前刷新状态和倒计时
    • 提供开始和停止刷新的按钮
  3. 清单文件 (manifest.json):
    • 配置插件的基本信息和权限
    • 注册后台脚本和弹出窗口

 

使用方法:

 

  1. 打开 Chrome 浏览器,访问 chrome://extensions/
  2. 开启 "开发者模式"
  3. 点击 "加载已解压的扩展程序",选择插件所在目录
  4. 点击浏览器工具栏中的插件图标
  5. 设置刷新时间并点击 "开始刷新" 按钮

 

默认刷新时间为 15 分钟,标签页在后台也会按设置的时间自动刷新。
background.js
// 存储标签刷新配置的对象,格式:{ tabId: { interval: 900, nextRefresh: timestamp } }
const refreshConfigs = new Map();

// 监听标签页更新事件,当标签页URL变化时重置刷新配置
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.url && refreshConfigs.has(tabId)) {
        const config = refreshConfigs.get(tabId);
        config.nextRefresh = Date.now() + config.interval * 1000;
    }
});

// 监听标签页关闭事件,移除对应的刷新配置
chrome.tabs.onRemoved.addListener((tabId) => {
    refreshConfigs.delete(tabId);
});

// 定时检查需要刷新的标签页
setInterval(() => {
    const now = Date.now();
    refreshConfigs.forEach((config, tabId) => {
        if (config.nextRefresh <= now) {
            chrome.tabs.get(tabId, (tab) => {
                if (!chrome.runtime.lastError && tab) {
                    chrome.tabs.reload(tabId);
                    config.nextRefresh = now + config.interval * 1000;
                } else {
                    refreshConfigs.delete(tabId);
                }
            });
        }
    });
}, 1000); // 每秒检查一次

// 接收来自popup的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'setRefresh') {
        const tabId = message.tabId;
        const interval = message.interval;
        refreshConfigs.set(tabId, {
            interval: interval,
            nextRefresh: Date.now() + interval * 1000
        });
        sendResponse({ success: true });
    } else if (message.action === 'getRefresh') {
        const tabId = message.tabId;
        sendResponse({ config: refreshConfigs.get(tabId) });
    } else if (message.action === 'clearRefresh') {
        const tabId = message.tabId;
        refreshConfigs.delete(tabId);
        sendResponse({ success: true });
    }
});    

manifest.json

{
    "name": "标签页自动刷新",
    "version": "1.0",
    "description": "按标签页设置自动刷新时间,即使标签页不在激活状态也能自动刷新",
    "permissions": ["tabs", "activeTab", "background"],
    "background": {
        "service_worker": "background.js"
    },
    "action": {
        "default_popup": "popup.html",
        "default_title": "标签页自动刷新"
    },
    "manifest_version": 3
}    

popup.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>标签页自动刷新</title>
    <style>
        body {
            width: 280px;
            padding: 15px;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
        }
        .container {
            text-align: center;
        }
        .status {
            margin: 10px 0;
            padding: 5px;
            border-radius: 4px;
            font-weight: bold;
        }
        .active {
            background-color: #d4edda;
            color: #155724;
        }
        .inactive {
            background-color: #f8d7da;
            color: #721c24;
        }
        .time-display {
            font-size: 24px;
            margin: 15px 0;
            font-family: monospace;
        }
        .controls {
            margin-top: 15px;
        }
        input, select {
            padding: 6px 10px;
            margin: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            padding: 8px 15px;
            margin: 5px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        #stop {
            background-color: #f44336;
        }
        #stop:hover {
            background-color: #d32f2f;
        }
    </style>
</head>
<body>
    <div class="container">
        <h3>标签页自动刷新</h3>
        <div class="status inactive" id="status">自动刷新未开启</div>
        <div class="time-display" id="time-display">--:--</div>
        
        <div class="controls">
            <input type="number" id="interval" value="15" min="1">
            <select id="unit">
                <option value="seconds">秒</option>
                <option value="minutes" selected>分钟</option>
            </select>
            <br>
            <button id="start">开始刷新</button>
            <button id="stop">停止刷新</button>
        </div>
    </div>
    <script src="popup.js"></script>
</body>
</html>    

popup.js

document.addEventListener('DOMContentLoaded', () => {
    const intervalInput = document.getElementById('interval');
    const unitSelect = document.getElementById('unit');
    const startBtn = document.getElementById('start');
    const stopBtn = document.getElementById('stop');
    const statusText = document.getElementById('status');
    const timeDisplay = document.getElementById('time-display');

    let currentTabId = null;
    let currentConfig = null;
    let countdownInterval = null;

    // 获取当前激活的标签页
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs.length > 0) {
            currentTabId = tabs[0].id;
            updateStatus();
        }
    });

    // 计算剩余时间并更新显示
    function updateCountdown() {
        if (currentConfig) {
            const now = Date.now();
            const remaining = Math.max(0, Math.ceil((currentConfig.nextRefresh - now) / 1000));
            const minutes = Math.floor(remaining / 60);
            const seconds = remaining % 60;
            timeDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
    }

    // 更新状态显示
    function updateStatus() {
        chrome.runtime.sendMessage({ action: 'getRefresh', tabId: currentTabId }, (response) => {
            currentConfig = response.config;
            
            if (currentConfig) {
                // 显示当前配置
                statusText.textContent = '自动刷新已开启';
                statusText.className = 'status active';
                
                // 设置输入框值
                const minutes = currentConfig.interval / 60;
                if (minutes >= 1) {
                    intervalInput.value = minutes;
                    unitSelect.value = 'minutes';
                } else {
                    intervalInput.value = currentConfig.interval;
                    unitSelect.value = 'seconds';
                }
                
                // 开始倒计时显示
                updateCountdown();
                if (countdownInterval) clearInterval(countdownInterval);
                countdownInterval = setInterval(updateCountdown, 1000);
            } else {
                // 显示默认状态
                statusText.textContent = '自动刷新未开启';
                statusText.className = 'status inactive';
                timeDisplay.textContent = '--:--';
                if (countdownInterval) {
                    clearInterval(countdownInterval);
                    countdownInterval = null;
                }
            }
        });
    }

    // 开始刷新按钮点击事件
    startBtn.addEventListener('click', () => {
        const value = parseInt(intervalInput.value, 10);
        if (isNaN(value) || value <= 0) {
            alert('请输入有效的时间值');
            return;
        }

        let interval = value;
        if (unitSelect.value === 'minutes') {
            interval = value * 60; // 转换为秒
        }

        chrome.runtime.sendMessage({ 
            action: 'setRefresh', 
            tabId: currentTabId, 
            interval: interval 
        }, () => {
            updateStatus();
        });
    });

    // 停止刷新按钮点击事件
    stopBtn.addEventListener('click', () => {
        chrome.runtime.sendMessage({ action: 'clearRefresh', tabId: currentTabId }, () => {
            updateStatus();
        });
    });

    // 页面卸载时清理
    window.addEventListener('unload', () => {
        if (countdownInterval) {
            clearInterval(countdownInterval);
        }
    });
});    

 

posted on 2025-06-25 11:56  yjanb11  阅读(1560)  评论(0)    收藏  举报