Chrome扩展优化:仅在指定URL触发API调用的实现方法
解决方案
要实现仅在访问指定域名(如pythonewbie.com)时调用get_pending_cookies API,你需要在触发API调用前添加URL判断逻辑,具体修改如下:
1. 修正chrome.tabs.onUpdated监听逻辑
当前监听回调未判断标签页URL,且未正确执行handle_cookies函数。修改后通过事件参数直接获取标签页信息,只在目标域名下触发API调用:
// 替换原有的chrome.tabs.onUpdated监听 chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { // 仅在标签页加载完成且URL有效时执行 if (changeInfo.status === 'complete' && tab.url) { const targetDomain = 'pythonewbie.com'; try { const urlObj = new URL(tab.url); // 判断当前域名是否为目标域名或其子域名 const isTargetDomain = urlObj.hostname === targetDomain || urlObj.hostname.endsWith(`.${targetDomain}`); if (isTargetDomain) { // 从storage中获取已存储的discord_id chrome.storage.local.get('discord_id', (data) => { if (data.discord_id) { handle_cookies(data.discord_id); } }); } } catch (error) { // 处理无效URL的情况,直接跳过 return; } } });
2. 可选:在handle_cookies中追加二次校验
为了更严谨,可以在handle_cookies函数内再次确认当前标签页域名,避免意外调用:
function handle_cookies(discord_id) { // 先校验当前标签页域名 chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) { if (!tabs?.length) return; const currentUrl = tabs[0].url; if (!currentUrl) return; const targetDomain = 'pythonewbie.com'; try { const urlObj = new URL(currentUrl); const isTargetDomain = urlObj.hostname === targetDomain || urlObj.hostname.endsWith(`.${targetDomain}`); if (!isTargetDomain) return; // 非目标域名直接终止 // 域名校验通过后再调用API get_pending_cookies(discord_id).then((result) => { // 你的原有处理逻辑... // 原有的页面检测逻辑可以保留,也可以简化 if (tabs[0].url === url) { console.log("USER OPENED CORRECT PAGE, RELOADING"); chrome.tabs.reload(tabs[0].id); } }); } catch (error) { return; } }); }
3. 优化权限配置(可选)
在manifest.json中,将host_permissions从<all_urls>改为仅包含目标域名,提升扩展安全性:
"host_permissions": ["*://*.pythonewbie.com/*", "http://cookie.pynewbie.com/*"]
关键说明
- 使用
URL对象解析域名,避免直接用字符串includes导致的误判(比如其他域名包含pythonewbie.com字符的情况)。 - 仅在标签页
status为complete时触发,避免页面加载过程中重复调用。 - 从
chrome.storage.local获取discord_id,确保调用handle_cookies时有合法参数。
内容的提问来源于stack exchange,提问作者PythonNewbie
相关产品推荐
相关产品推荐

