【问题标题】:Chrome Extension Tabs onUpdated with status === 'complete' works too earlyChrome 扩展选项卡 onUpdated with status === \'complete\' 工作得太早了
【发布时间】: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


【解决方案1】:
var exUrl = ''    

if (changeInfo.status === 'complete' && exUrl != tab.url) {
    exUrl = tab.url;
}

好吧,我用了这个技巧。
也许 changInfo.status 部分发送完整的信号?
我不知道到底发生了什么,但这对我有用

【讨论】:

    猜你喜欢
    • 2017-03-20
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 2012-03-14
    • 1970-01-01
    相关资源
    最近更新 更多