这是我的第一个 Chrome 扩展,这就是我所做的。 扩展的目的是下载某些网页的源代码,然后在几秒钟后刷新页面,等等。这使我能够每 10 秒获取这些页面的文本格式的源代码,并使用软件对其进行分析以检测任何更改。 然而,我的印象是浏览器随着时间的推移变得越来越慢。 由于这是我第一次完成 JavaScript 和浏览器扩展,所以我不确定我是否做对了。 有一些代码我不明白(那些标记为 idk 的代码)。
这是我的代码:
{
"manifest_version": 2,
"name": "YggRSS",
"version": "1.0",
"description": "Obtention du flux RSS depuis Yggtorrent",
"permissions": ["tabs", "activeTab", "http://*/*", "https://*/*","downloads","management"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": "icon.png",
"default_title": "YggRSS"
}
}
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
// Check if this is my target
var expression = /mywebsite.*status/;
if (expression.test(tab.url)) {
// Get source code
fetch(tab.url)
.then(response => response.text())
.then(data => {
// Check if sourcecode contains statusdetails
if (data.includes("atom-78")) {
// File name will be like sc_78_.txt for a page with the id 78
const match = tab.url.match(/id=(\d+)/);
if (match && match[1]) {
const id = match[1];
const filename = 'sc_' + id + '_' + '.txt';
// Idk but it works
const blob = new Blob([data], { type: 'text/plain' });
const urlData = URL.createObjectURL(blob);
// Download the file
chrome.downloads.download({
url: urlData,
filename: filename,
conflictAction: 'uniquify',
saveAs: false
}, (downloadId) => {
// // After 8s, remload (don't works with more that 10s)
setTimeout(() => {
chrome.tabs.update(tabId, { url: tab.url });
}, 8000);
});
// Idk but looks required
URL.revokeObjectURL(urlData);
} else {
alert('No id found.');
}
} else {
// Page load fail, reload
setTimeout(() => {
chrome.tabs.update(tabId, { url: tab.url });
}, 10000);
}
})
.catch(error => {
alert('Unknown error', error);
});
}
}
});
更改超时设置,以便一次只有一个活动
let tId;
chrome.tabs.onUpdated.addListener
...
clearTimeout(tId)
tId = setTimeout(() => {
chrome.tabs.update(tabId, { url: tab.url });
}, 8000);
...
else {
clearTimeout(tId)
tId = setTimeout(() => {
chrome.tabs.update(tabId, { url: tab.url });
}, 10000);