在chrome扩展background.js文件中有这段代码,它应该只在单击我在服务工作线程中使用contentScript.js加载到页面上的按钮时运行,每次按下按钮我只看到4个API调用(页面上有两个视频),我不可能使用这个超过 500 次,更不用说每天 10,000 次了,但我已经达到了配额限制。有什么想法吗?
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'SEARCH_YOUTUBE') {
const title = request.title;
console.log('about to call searchyoutube w/ title: ' + title);
searchYouTube(title)
.then(viewCount => {
sendResponse({ viewCount });
})
.catch(err => {
console.error('Error searching YouTube:', err);
sendResponse({ viewCount: null });
});
return true; // Keep the message channel open for async response
}
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'SEARCH_YOUTUBE') {
const title = request.title;
console.log('about to call searchYouTube w/ title: ' + title);
searchYouTube(title)
.then(viewCount => {
sendResponse({ viewCount });
})
.catch(err => {
console.error('Error searching YouTube:', err);
sendResponse({ viewCount: null });
});
return true; // Keep the message channel open for async response
}
});
async function searchYouTube(query) {
console.log('YouTube search is running with query: ' + query);
const searchUrl = `https://www.googleapis.com/youtube/v3/search?part=snippet&q=${encodeURIComponent(query)}&type=video&key=${API_KEY}&maxResults=1`;
const searchResp = await fetch(searchUrl);
const searchData = await searchResp.json();
if (!searchData.items || searchData.items.length === 0) {
return null; // No results found
}
const videoItem = searchData.items[0];
const videoTitle = videoItem.snippet.title.trim();
// Check if the query matches the video title exactly
console.log(decodeHtml(query) + ' vs ' + decodeHtml(videoTitle));
if (decodeHtml(videoTitle).toLowerCase() !== decodeHtml(query).toLowerCase()) {
return null; // No exact match
}
const videoId = videoItem.id.videoId;
// Get video statistics
const statsUrl = `https://www.googleapis.com/youtube/v3/videos?part=statistics&id=${videoId}&key=${API_KEY}`;
const statsResp = await fetch(statsUrl);
const statsData = await statsResp.json();
if (!statsData.items || statsData.items.length === 0) {
return null;
}
const viewCount = statsData.items[0].statistics.viewCount;
return viewCount;
}
function decodeHtml(html) {
const entities = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
// Add more entities as needed
};
return html.replace(/&[a-zA-Z0-9#]+;/g, (match) => entities[match] || match);
}
按照配额费用页面 搜索列表需要100个配额点。
10000 / 100 = 100
这意味着您每天最多可以拨打 100 个电话。 配额在午夜重置,以美国时间为准。 因为您使用 JavaScript,即使刷新页面也会重新运行调用。
记住这10k是开发配额。 您可以申请延期。