【发布时间】:2022-10-24 02:47:43
【问题描述】:
背景.js
// create a new tab when alarmed
chrome.alarms.onAlarm.addListener(function(alarm) {
if (alarm.name === 'myAlarm') {
let tabId = 0;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
const url = 'https://www.vk.com/feed';
chrome.tabs.create({ url }, (tab) => {
tabId = tab.id!;
});
});
}
});
// wait till the new tab will load completely to do the stuff with DOM in the new tab from content.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (tab.url!.indexOf('https://www.vk.com/feed') != -1 && changeInfo.status == 'complete') {
// setTimeout
chrome.tabs.sendMessage(tabId, {
from: Sender.React,
message: 'GET_COOKIES'
});
}
});
我已经尝试了上面的这段代码,但它不起作用 当 DOM 未准备好时,我收到状态 === 'complete' 并过早向我的 content.js 发送消息(content.js 找不到元素并且在收到'GET_COOKIES'消息时不做任何事情) 当我添加 setTimeout 时,例如 3000 毫秒用于发送消息 - 效果很好! 但我不想这样做,因为有些用户的连接不稳定,他们需要超过 3 秒,而有些用户则需要不到 3 秒,连接更好 我已经用 'webNavigation' 尝试过 'onHistoryStateUpdated' - 但它似乎也不起作用
我应该如何解决这个问题? 请帮忙...
【问题讨论】:
-
现代网站添加元素后DOM 是完整的(从初始服务器响应构建的 DOM)。使用 MutationObserver 等待内容脚本中的元素。
标签: javascript google-chrome-extension