擴(kuò)展background.js中fetch隊(duì)列泡垃,用來后臺(tái)請(qǐng)求控制

簡(jiǎn)單的fetch并行改串行控制

/**
 *  基于fetch的并行控制
 * 【鄭重聲明】 該代碼著作權(quán)歸瞌睡蟲子所有纺念。其他第三方使用該代碼用于商用活動(dòng),引起的法律糾紛與作者無關(guān),同時(shí)作者保留追責(zé)權(quán)力曾沈。
 *
 *  2024-12-29
 *  后臺(tái)这嚣,序列http下載,后臺(tái)爬蟲框架http部分
 * ____________________________________________________________________________________________________________________________________
 */
// 隊(duì)列抓取限制抓取并發(fā)
class FetchQueue {
    constructor(maxConcurrentRequests, interval = 1000) {
        console.log("創(chuàng)建爬蟲");
        this.maxConcurrentRequests = maxConcurrentRequests;
        this.currentlyRunning = 0;
        this.queue = [];
        this.interval = interval;
    }

    add(url) {
        return new Promise((resolve, reject) => {
            const task = () => {
                setTimeout(() => {
                    if (this.currentlyRunning < this.maxConcurrentRequests) {
                        this.currentlyRunning++;

                        // 這里添加異步隊(duì)列批量處理方法
                        fetch(url)
                        .then(response => response.text())
                        .then(data => {
                            this.currentlyRunning--;
                            resolve(data);
                            this.next();
                        })
                        .catch(error => {
                            this.currentlyRunning--;
                            reject(error);
                            this.next();
                        });

                    } else {
                        this.queue.push(task);
                    }
                }, this.interval);
            };

            if (this.currentlyRunning < this.maxConcurrentRequests) {
                task();
            } else {
                this.queue.push(task);
            }
        });
    }

    next() {
        if (this.queue.length > 0 && this.currentlyRunning < this.maxConcurrentRequests) {
            const task = this.queue.shift();
            task();
        }
    }
}

接受content.js的消息塞俱,控制后臺(tái)下載姐帚,返回給content.js渲染都界面
backgroud.js

// 使用 FetchQueue,并設(shè)置不同的間隔時(shí)間 1 障涯, 600
const maxConcurrentRequests = 1; // 設(shè)置最大并發(fā)請(qǐng)求數(shù)
const fetchQueue = new FetchQueue(maxConcurrentRequests, 620);

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.method === "fetchUrl") {

        // 將 fetch 請(qǐng)求添加到隊(duì)列
        fetchQueue.add(request.url)
        .then(function (html) {

            // 使用正則表達(dá)式抽取人氣值
            var regex = /(\d+)\s*人次/;
            var match = html.match(regex);
            if (match && match[1]) {
                // match[1] 就是人氣值
                var popularity = match[1];
                sendResponse({
                    id: request.id,
                    msg: popularity,
                    flag: true
                });
                // console.log('人氣值:', popularity);
            } else {
                sendResponse({
                    id: request.id,
                    msg: "未找到人氣值",
                    flag: false
                });
                console.log('未找到人氣值');
            }
        })
        .catch(error => sendResponse({
                id: request.id,
                msg: "請(qǐng)求失敗",
                flag: false
            }));
        return true; // 表示響應(yīng)是異步的
    } else if (request.method === "clear") {
        fetchQueue.queue = [];
        sendResponse({
            msg: "隊(duì)列清空成功",
            flag: true
        })
        return false; // 不處理
    } else if (message.method === "openPopup") {
        chrome.action.openPopup();
    }
    return false; // 不處理
});

// 激活標(biāo)簽頁(yè)
chrome.tabs.onActivated.addListener(function (activeInfo) {
    // 你可以獲取激活的標(biāo)簽頁(yè)的詳細(xì)信息
    chrome.tabs.get(activeInfo.tabId, function (tab) {
        // 在這里你可以根據(jù)激活的標(biāo)簽頁(yè)執(zhí)行一些操作
        if (tab.url.match(/目標(biāo)網(wǎng)頁(yè)/)) {
            console.log('Active tab URL: ' + tab.url);
            chrome.tabs.sendMessage(activeInfo.tabId, {
                method: "clear"
            });
        }
    });
});

與backgroud.js通訊罐旗,發(fā)送任務(wù)消息等待結(jié)果,再渲染
contet.js

/**
 *  瞌睡蟲子
 *
 *  2024-11-5
 *  人氣值抓去顯示
 */

console.log('開始工作啦:', location.href);

// 隨機(jī)唯一ID
function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
        v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function getRQ() {
    var res = {}
    document.querySelectorAll("li em a:not([class='fetch'])").forEach(function (dd) {
        // 獲取當(dāng)前元素的 'href' 屬性
        var url = dd.href;
        var uuid = "L_" + generateUUID();
        res[uuid] = dd;
        // console.log(url);

        chrome.runtime.sendMessage({
            method: "fetchUrl",
            url: url,
            id: uuid
        }, function (response) {
            var id = response.id;
            var msg = response["msg"];
            if (msg && res[id] && response.flag) {
                var node = res[id];
                node.className += "fetch";
                node.parentElement.nextElementSibling.innerHTML += '&emsp;<span style="font-weight: normal;font-size: 12px;color: black;">人氣:' + msg + "</span>";
                res[id] = undefined;
            }
        });
    });
}

var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
const options = {
    childList: true
    // attributes: true,
    // characterData: true,
    // subtree: true,
    // attributeOldValue: true,
    // characterDataOldValue: true
};
// 創(chuàng)建MutationObserver實(shí)例唯蝶,返回一個(gè)觀察者對(duì)象
const mutation = new MutationObserver(function (mutationRecoards, observer) {
    for (const recoard of mutationRecoards) {
        if (recoard.type === 'childList') {
            // getRQ(recoard.addedNodes);
            // setTimeout(getRQ, 500);
            console.log("加載新數(shù)據(jù)…");

            setTimeout(function () {
                var res = {};
                recoard.addedNodes.forEach(function (dd) {
                    if (dd.nodeType == 1 && dd.nodeName == "LI") {

                        // 獲取當(dāng)前元素的 'href' 屬性
                        var aa = dd.querySelector("em a");
                        var url = aa.href;
                        var uuid = "L_" + generateUUID();
                        res[uuid] = aa;
                        // console.log(url);

                        chrome.runtime.sendMessage({
                            method: "fetchUrl",
                            url: url,
                            id: uuid
                        }, function (response) {
                            var id = response.id;
                            var msg = response["msg"];
                            if (msg && res[id] && response.flag) {
                                var node = res[id];
                                node.className += "fetch";
                                node.parentElement.nextElementSibling.innerHTML += '&emsp;<span style="font-weight: normal;font-size: 12px;color: black;">人氣:' + msg + "</span>";
                                res[id] = undefined;
                            }
                        });
                    };
                });
            }, 500);
        }
    }
});

// 當(dāng)前頁(yè)面激活
// content.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message && message.method === "clear") {
        // 標(biāo)簽頁(yè)被激活九秀,執(zhí)行相關(guān)操作
        console.log("頁(yè)面激活,繼續(xù)抓取…");
        try {
            chrome.runtime.sendMessage({
                method: "clear"
            },function(response) {
                getRQ();
            });
        } catch (error) {
            
        }
    }
    return false;
});

// 對(duì)觀察者添加需要觀察的元素粘我,并設(shè)置需要觀察元素的哪些方面
document.querySelectorAll('ul').forEach(function (targetElement) {
    mutation.observe(targetElement, options);
});

// 清空爬取隊(duì)列
chrome.runtime.sendMessage({
    method: "clear"
});
// 發(fā)消息請(qǐng)求
getRQ();

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末鼓蜒,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子征字,更是在濱河造成了極大的恐慌都弹,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,204評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件匙姜,死亡現(xiàn)場(chǎng)離奇詭異畅厢,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)氮昧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門或详,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人郭计,你說我怎么就攤上這事霸琴。” “怎么了昭伸?”我有些...
    開封第一講書人閱讀 164,548評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵梧乘,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我庐杨,道長(zhǎng)选调,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,657評(píng)論 1 293
  • 正文 為了忘掉前任灵份,我火速辦了婚禮仁堪,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘填渠。我一直安慰自己弦聂,他們只是感情好鸟辅,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著莺葫,像睡著了一般匪凉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上捺檬,一...
    開封第一講書人閱讀 51,554評(píng)論 1 305
  • 那天再层,我揣著相機(jī)與錄音,去河邊找鬼堡纬。 笑死聂受,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的烤镐。 我是一名探鬼主播饺饭,決...
    沈念sama閱讀 40,302評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼职车!你這毒婦竟也來了瘫俊?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,216評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤悴灵,失蹤者是張志新(化名)和其女友劉穎扛芽,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體积瞒,經(jīng)...
    沈念sama閱讀 45,661評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡川尖,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了茫孔。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片叮喳。...
    茶點(diǎn)故事閱讀 39,977評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖缰贝,靈堂內(nèi)的尸體忽然破棺而出馍悟,到底是詐尸還是另有隱情,我是刑警寧澤剩晴,帶...
    沈念sama閱讀 35,697評(píng)論 5 347
  • 正文 年R本政府宣布锣咒,位于F島的核電站,受9級(jí)特大地震影響赞弥,放射性物質(zhì)發(fā)生泄漏毅整。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評(píng)論 3 330
  • 文/蒙蒙 一绽左、第九天 我趴在偏房一處隱蔽的房頂上張望悼嫉。 院中可真熱鬧,春花似錦拼窥、人聲如沸戏蔑。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)辛臊。三九已至仙粱,卻和暖如春房交,著一層夾襖步出監(jiān)牢的瞬間彻舰,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工候味, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留刃唤,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,138評(píng)論 3 370
  • 正文 我出身青樓白群,卻偏偏與公主長(zhǎng)得像尚胞,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子帜慢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容